Index: /issm/trunk/configs/config-arm-linux.sh
===================================================================
--- /issm/trunk/configs/config-arm-linux.sh	(revision 13974)
+++ /issm/trunk/configs/config-arm-linux.sh	(revision 13975)
@@ -6,6 +6,8 @@
     --host="arm-linux-androideabi" \
     --enable-shared \
+    --with-android=jni\
     --without-fortran \
-	--without-modules \
+	--without-wrappers \
+	--without-kriging \
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
Index: /issm/trunk/configs/config-discover.sh
===================================================================
--- /issm/trunk/configs/config-discover.sh	(revision 13974)
+++ /issm/trunk/configs/config-discover.sh	(revision 13975)
@@ -22,5 +22,5 @@
  --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
  --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-O3 -xS" \
+ --with-cxxoptflags="-O3 -xS -DMPICH_IGNORE_CXX_SEEK" \
  --with-vendor=intel-discover
 
Index: /issm/trunk/configs/config-greenplanet.sh
===================================================================
--- /issm/trunk/configs/config-greenplanet.sh	(revision 13974)
+++ /issm/trunk/configs/config-greenplanet.sh	(revision 13975)
@@ -6,5 +6,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-modules=no \
+ --with-wrappers=no \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
Index: /issm/trunk/configs/config-linux64-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-ad.sh	(revision 13974)
+++ /issm/trunk/configs/config-linux64-ad.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--without-modules\
+	--without-wrappers\
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
 	--without-thermal \
Index: sm/trunk/configs/config-linux64-astrid-python.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid-python.sh	(revision 13974)
+++ 	(revision )
@@ -1,25 +1,0 @@
-#!/bin/sh
-
-#External packages versions:
-#petsc 3.1 or 3.2
-#mpich 1.4
-
-./configure \
- --prefix=$ISSM_DIR \
- --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
- --with-python-dir=$ISSM_DIR/externalpackages/python/install\
- --with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
- --with-python-version=2.7\
- --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
- --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
- --with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich " \
- --with-petsc-arch=$ISSM_ARCH \
- --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
- --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/4.1.1/ -lgfortran" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-march=opteron -O2 -lutil" \
- --with-numthreads=32 \
- --enable-debugging
Index: /issm/trunk/configs/config-linux64-astrid.sh
===================================================================
--- /issm/trunk/configs/config-linux64-astrid.sh	(revision 13974)
+++ /issm/trunk/configs/config-linux64-astrid.sh	(revision 13975)
@@ -13,5 +13,4 @@
  --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 \
Index: /issm/trunk/configs/config-linux64-cloud.sh
===================================================================
--- /issm/trunk/configs/config-linux64-cloud.sh	(revision 13975)
+++ /issm/trunk/configs/config-linux64-cloud.sh	(revision 13975)
@@ -0,0 +1,20 @@
+#!/bin/sh
+
+#External packages versions:
+#petsc 3.1 or 3.2
+#mpich 1.4
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --without-wrappers \
+ --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-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-cxxoptflags=" -O2 -fpermissive" 
Index: /issm/trunk/configs/config-linux64-murdo-ad.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo-ad.sh	(revision 13974)
+++ /issm/trunk/configs/config-linux64-murdo-ad.sh	(revision 13975)
@@ -2,36 +2,9 @@
 
 ./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-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-ml-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
- --with-fortran-lib="-L/usr/lib/gcc/x86_64-redhat-linux/3.4.6/ -lg2c  /usr/lib/gcc/x86_64-redhat-linux/4.1.1/libgfortran.a" \
- --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-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install
Index: /issm/trunk/configs/config-linux64-murdo.sh
===================================================================
--- /issm/trunk/configs/config-linux64-murdo.sh	(revision 13974)
+++ /issm/trunk/configs/config-linux64-murdo.sh	(revision 13975)
@@ -1,26 +1,27 @@
 #!/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="-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-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
- --with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
- --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
- --with-numthreads=18 \
- --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
- --enable-debugging
- 
- 
+	--prefix=$ISSM_DIR \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
+	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
+	--with-mpi-lib="-L$ISSM_DIR/externalpackages/mpich2/install/lib/ -lmpich" \
+	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
+	--with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+	--with-petsc-arch=$ISSM_ARCH \
+	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-scotch-dir="$ISSM_DIR/externalpackages/scotch/install" \
+	--with-graphics-lib=/usr/lib64/libX11.so \
+	--with-cxxoptflags="-mtune=barcelona -ffast-math -O3 -msse4.2 -Wno-write-strings "\
+	--with-numthreads=18 \
+	--enable-debugging 
Index: /issm/trunk/configs/config-macosx-snowleopard-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx-snowleopard-bothapis.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx-snowleopard-bothapis.sh	(revision 13975)
@@ -3,11 +3,4 @@
 #petsc 3.2
 #mpich 1.4
-
-#export FCFLAGS=" -m32"
-#export FFLAGS=" -m32"
-#export CFLAGS=" -arch i386"
-#export CXXFLAGS=" -arch i386"
-
-pythonversion=2.7
 
 ./configure \
@@ -16,6 +9,5 @@
 	--with-matlab-dir=$MATLAB_DIR \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-version=$pythonversion \
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
Index: /issm/trunk/configs/config-macosx-snowleopard-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx-snowleopard-python.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx-snowleopard-python.sh	(revision 13975)
@@ -4,12 +4,9 @@
 #mpich 1.4
 
-pythonversion=2.7
-
 ./configure \
 	--prefix=$ISSM_DIR \
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-version=$pythonversion \
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
Index: /issm/trunk/configs/config-macosx64-ad.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-ad.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-ad.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--without-modules\
+	--without-wrappers\
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install\
 	--without-thermal \
Index: /issm/trunk/configs/config-macosx64-chris-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-bothapis.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-chris-bothapis.sh	(revision 13975)
@@ -4,18 +4,15 @@
 #mpich 1.4
 
-pythonversion=2.7
-
 ./configure \
 	--prefix=$ISSM_DIR \
+	--with-matlab-dir=$MATLAB_DIR \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install \
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy\
 	--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-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
 	--with-math-lib="/usr/lib/libm.dylib" \
 	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
@@ -28,6 +25,3 @@
 	--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/ \
+	#--with-fortran-lib="/usr/local/gfortran/lib/gcc/x86_64-apple-darwin10/4.6.2/libgfortran.a" \
Index: /issm/trunk/configs/config-macosx64-chris-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-chris-python.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-chris-python.sh	(revision 13975)
@@ -4,12 +4,9 @@
 #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-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
@@ -24,11 +21,6 @@
 	--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: /issm/trunk/configs/config-macosx64-gsl.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-gsl.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-gsl.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
 	--prefix=$ISSM_DIR \
-	--without-modules\
+	--without-wrappers\
 	--with-gsl-dir=$ISSM_DIR/externalpackages/gsl/install
 	#--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install 
Index: /issm/trunk/configs/config-macosx64-larour-ad.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-ad.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-larour-ad.sh	(revision 13975)
@@ -1,3 +1,5 @@
 #!/bin/sh
+
+pythonversion=2.7
 
 ./configure \
@@ -8,4 +10,6 @@
 	--with-adolc-dir=$ISSM_DIR/externalpackages/adolc/install \
 	--with-matlab-dir=$MATLAB_DIR \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 
Index: sm/trunk/configs/config-macosx64-larour-bothapis.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-bothapis.sh	(revision 13974)
+++ 	(revision )
@@ -1,33 +1,0 @@
-#!/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/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
-	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
-	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
-	--with-mpi-lib=" $ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
-	--with-chaco-dir=$ISSM_DIR/externalpackages/chaco/install \
-	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
-	--with-math-lib="/usr/lib/libm.dylib" \
-	--with-graphics-lib="/usr/X11/lib/libX11.dylib" \
-	--with-cxxoptflags=" -fno-common -no-cpp-precomp -fexceptions -arch x86_64 -mmacosx-version-min=10.5  -O3 -DNDEBUG -w "\
-	--with-numthreads=8 \
-	--with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install  \
-	--with-petsc-arch=$ISSM_ARCH \
-	--with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
-	--with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
-	--with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/install/include/ " \
-	--with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
-	--with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ 
-	#--with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
-	#--with-boost-dir=$ISSM_DIR/externalpackages/boost/install/ \
Index: /issm/trunk/configs/config-macosx64-larour-nopetsc.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-nopetsc.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-larour-nopetsc.sh	(revision 13975)
@@ -1,5 +1,3 @@
 #!/bin/sh
-
-pythonversion=3.2
 
 ./configure \
@@ -7,6 +5,5 @@
 	--with-matlab-dir=$MATLAB_DIR \
 	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
-	--with-python-version=$pythonversion \
-	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Python.framework/Versions/3.2/lib/python3.2/site-packages/numpy/core/include/numpy\
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-math-lib="/usr/lib/libm.dylib" \
Index: /issm/trunk/configs/config-macosx64-larour-python.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour-python.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-larour-python.sh	(revision 13975)
@@ -4,12 +4,9 @@
 #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-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
Index: /issm/trunk/configs/config-macosx64-larour.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-larour.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-larour.sh	(revision 13975)
@@ -4,7 +4,11 @@
 #mpich 1.4
 
+pythonversion=2.7
+
 ./configure \
 	--prefix=$ISSM_DIR \
 	--with-matlab-dir=$MATLAB_DIR \
+	--with-python-dir=$ISSM_DIR/externalpackages/python/install\
+	--with-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/Library/Frameworks/Python.framework/Versions/$pythonversion/lib/python$pythonversion/site-packages/numpy/core/include/numpy\
 	--with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
@@ -20,6 +24,4 @@
 	--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/ \
Index: /issm/trunk/configs/config-macosx64-lion-helene.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-lion-helene.sh	(revision 13974)
+++ /issm/trunk/configs/config-macosx64-lion-helene.sh	(revision 13975)
@@ -3,6 +3,4 @@
 #petsc 3.2
 #mpich 1.4
-
-pythonversion=2.7
 
 ./configure \
@@ -11,6 +9,5 @@
 	--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-python-numpy-dir=$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy\
 	--with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
 	--with-mpi-include=$ISSM_DIR/externalpackages/mpich2/install/include  \
Index: /issm/trunk/configs/config-macosx64-mlion-mathieu.sh
===================================================================
--- /issm/trunk/configs/config-macosx64-mlion-mathieu.sh	(revision 13975)
+++ /issm/trunk/configs/config-macosx64-mlion-mathieu.sh	(revision 13975)
@@ -0,0 +1,25 @@
+#!/bin/sh
+
+#mpich  1.5
+#petsc  3.3
+#python 2.7
+
+./configure \
+	--prefix="$ISSM_DIR" \
+	--with-matlab-dir="$ISSM_DIR/externalpackages/matlab/install" \
+	--with-triangle-dir="$ISSM_DIR/externalpackages/triangle/install" \
+	--with-python-dir="$ISSM_DIR/externalpackages/python/install" \
+	--with-python-numpy-dir="$ISSM_DIR/externalpackages/python/install/lib/python2.7/site-packages/numpy/core/include/numpy" \
+	--with-mpi-include="$ISSM_DIR/externalpackages/mpich2/install/include"  \
+	--with-mpi-lib="$ISSM_DIR/externalpackages/mpich2/install/lib/libpmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpich.a $ISSM_DIR/externalpackages/mpich2/install/lib/libmpl.a " \
+	--with-chaco-dir="$ISSM_DIR/externalpackages/chaco/install" \
+	--with-fortran-lib="/usr/local/gfortran/lib/libgfortran.a" \
+	--with-graphics-lib="-L/usr/X11R6/lib -lX11" \
+	--with-petsc-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-petsc-arch="$ISSM_ARCH" \
+	--with-blas-lapack-dir="$ISSM_DIR/externalpackages/petsc/install" \
+	--with-blacs-dir="$ISSM_DIR/externalpackages/petsc/install/" \
+	--with-scalapack-dir="$ISSM_DIR/externalpackages/petsc/install/" \
+	--with-mumps-dir="$ISSM_DIR/externalpackages/petsc/install/" \
+	--with-metis-dir="$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3" \
+	--with-numthreads=16
Index: /issm/trunk/configs/config-pleiades-petsc2.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc2.sh	(revision 13974)
+++ /issm/trunk/configs/config-pleiades-petsc2.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-modules=no \
+ --with-wrappers=no \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
Index: /issm/trunk/configs/config-pleiades-petsc3.3.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petsc3.3.sh	(revision 13975)
+++ /issm/trunk/configs/config-pleiades-petsc3.3.sh	(revision 13975)
@@ -0,0 +1,21 @@
+#!/bin/csh
+
+./configure \
+ --prefix=$ISSM_DIR \
+ --with-wrappers=no \
+ --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
+ --with-metis-dir=$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3 \
+ --with-petsc-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-tao-dir=$ISSM_DIR/externalpackages/tao/install \
+ --with-mpi-include=/nasa/sgi/mpt/2.06a67/include \
+ --with-mpi-lib="-L/nasa/sgi/mpt/2.06a67/lib/ -lmpi -lpthread -lgfortran " \
+ --with-petsc-arch=$ISSM_ARCH \
+ --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
+ --with-blas-lapack-dir=$ISSM_DIR/externalpackages/petsc/install \
+ --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-blacs-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
+ --with-graphics-lib=/usr/lib64/libX11.so \
+ --with-cxxoptflags="-O3" \
+ --with-vendor=intel-pleiades
Index: /issm/trunk/configs/config-pleiades-petscdev.sh
===================================================================
--- /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 13974)
+++ /issm/trunk/configs/config-pleiades-petscdev.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-modules=no \
+ --with-wrappers=no \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/petsc/src/externalpackages/metis-5.0.2-p3 \
@@ -13,6 +13,4 @@
  --with-dakota-dir=$ISSM_DIR/externalpackages/dakota/install \
  --with-mkl-dir=/nasa/intel/mkl/10.0.011/lib/64/ \
- --with-plapack-lib="-L$ISSM_DIR/externalpackages/petsc/install/ -lPLAPACK" \
- --with-plapack-include="-I$ISSM_DIR/externalpackages/petsc/src/externalpackages/PLAPACKR32-hg/INCLUDE" \
  --with-mumps-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-scalapack-dir=$ISSM_DIR/externalpackages/petsc/install/ \
@@ -20,9 +18,8 @@
  --with-spai-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-hypre-dir=$ISSM_DIR/externalpackages/petsc/install/ \
- --with-prometheus-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-superlu-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-spooles-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-pastix-dir=$ISSM_DIR/externalpackages/petsc/install/ \
  --with-graphics-lib=/usr/lib64/libX11.so \
- --with-cxxoptflags="-O3 -xS" \
+ --with-cxxoptflags="-O3" \
  --with-vendor=intel-pleiades
Index: /issm/trunk/configs/config-pleiades.sh
===================================================================
--- /issm/trunk/configs/config-pleiades.sh	(revision 13974)
+++ /issm/trunk/configs/config-pleiades.sh	(revision 13975)
@@ -3,5 +3,5 @@
 ./configure \
  --prefix=$ISSM_DIR \
- --with-modules=no \
+ --with-wrappers=no \
  --with-triangle-dir=$ISSM_DIR/externalpackages/triangle/install \
  --with-metis-dir=$ISSM_DIR/externalpackages/metis/install \
Index: /issm/trunk/configure.ac
===================================================================
--- /issm/trunk/configure.ac	(revision 13974)
+++ /issm/trunk/configure.ac	(revision 13975)
@@ -2,5 +2,5 @@
 
 #AUTOCONF
-AC_INIT([ISSM],[4.2.2],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
+AC_INIT([ISSM],[4.2.3],[issm@jpl.nasa.gov],[issm],[http://issm.jpl.nasa.gov]) #Initializing configure
 AC_CONFIG_AUX_DIR([./aux-config])         #Put config files in aux-config
 AC_CONFIG_MACRO_DIR([m4])                 #m4 macros are located in m4
@@ -36,7 +36,9 @@
 			src/Makefile
 			src/c/Makefile 
-			src/modules/Makefile
-			src/modules/python/Makefile
-			src/modules/matlab/Makefile
+			src/wrappers/Makefile
+			src/wrappers/python/Makefile
+			src/wrappers/matlab/Makefile
+			src/android/Makefile
+			src/android/ISSM/Makefile
 			src/m/Makefile])
 
Index: /issm/trunk/etc/environment.csh
===================================================================
--- /issm/trunk/etc/environment.csh	(revision 13974)
+++ /issm/trunk/etc/environment.csh	(revision 13975)
@@ -88,5 +88,5 @@
 set CMAKE_DIR="$ISSM_DIR/externalpackages/cmake/install"
 if (-d $CMAKE_DIR) then
-	setenv PATH {$PATH}:{$CMAKE_DIR}/bin
+	setenv PATH {$CMAKE_DIR}/bin:{$PATH}
 endif
 
Index: /issm/trunk/etc/environment.sh
===================================================================
--- /issm/trunk/etc/environment.sh	(revision 13974)
+++ /issm/trunk/etc/environment.sh	(revision 13975)
@@ -3,5 +3,5 @@
 pathprepend(){ #{{{
 	if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
-		PATH="$1:$PATH"
+		export PATH="$1:$PATH"
 	fi
 } #}}}
@@ -66,7 +66,9 @@
 
 MPI_DIR="$ISSM_DIR/externalpackages/mpich2/install"
-export MPI_DIR
-pathprepend   "$MPI_DIR/bin"
-libpathappend "$MPI_DIR/lib"
+if [ -d "$MPI_DIR" ]; then
+	export MPI_DIR
+	pathprepend   "$MPI_DIR/bin"
+	libpathappend "$MPI_DIR/lib"
+fi
 
 PETSC_DIR="$ISSM_DIR/externalpackages/petsc/install"
@@ -102,5 +104,5 @@
 
 GDAL_DIR="$ISSM_DIR/externalpackages/gdal/install"
-pathprepend "$GDAL_DIR/bin:$PATH"
+pathprepend "$GDAL_DIR/bin"
 libpathappend "$GDAL_DIR/lib"
 
@@ -187,8 +189,11 @@
 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"
+#android-dev-dir
+export ANDROID_DIR="$ISSM_DIR/externalpackages/android"
+
+export ANDROID_NDK_DIR="$ANDROID_DIR/android-ndk/install"
+pathappend "$ANDROID_NDK_DIR/arm-linux-android-install/bin"
+
+export ANDROID_SDK_DIR="$ANDROID_DIR/android-sdk/install"
 pathappend "$ANDROID_SDK_DIR/"
 
@@ -212,5 +217,5 @@
 
 GIT_DIR="$ISSM_DIR/externalpackages/git/install"
-pathappend "$GIT_DIR/bin"
+pathprepend "$GIT_DIR/bin"
 
 NCVIEW_DIR="$ISSM_DIR/externalpackages/ncview/install"
Index: /issm/trunk/externalpackages/adolc/install-2.2.0.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-2.2.0.sh	(revision 13975)
+++ /issm/trunk/externalpackages/adolc/install-2.2.0.sh	(revision 13975)
@@ -0,0 +1,60 @@
+#!/bin/bash
+set -eu
+
+#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
+
+#Some cleanup
+rm -rf install ADOL-C-2.2.0 src trunk
+
+#Create install directories
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
+
+#Untar 
+tar -zxvf  ADOL-C-2.2.0.tar.gz
+
+#Move ADOL-C into install directory
+mv ADOL-C-2.2.0/* src
+rm -rf ADOL-C-2.2.0
+
+#Compile ADOL-C
+cd src 
+
+#export CC=gcc
+#export CXX=g++
+#export CFLAGS="-arch x86_64"
+#export CXXFLAGS="-arch x86_64"
+
+./configure \
+	--prefix=$ISSM_DIR/externalpackages/adolc/install \
+	--enable-sparse \
+	--enable-docexa \
+	--enable-addexa \
+	--disable-shave
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
+
+
+#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
+#in all Makefiles
+for i in `find ./ -name Makefile `
+do
+	echo $i
+	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
+	mv $i.bak $i
+done
+
+#remake: 
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/adolc/install-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-dev.sh	(revision 13974)
+++ /issm/trunk/externalpackages/adolc/install-dev.sh	(revision 13975)
@@ -3,10 +3,10 @@
 
 #Some cleanup
-rm -rf install adolc_v220_issm
+rm -rf install adolc*issm
 
-git clone -b 2.3.x_ISSM  git://gitorious.org/~utke/adol-c/adolc_v220_issm.git 
+git clone -b 2.3.x_ISSM  git://git.mcs.anl.gov/adol-c.git adolc_issm
 
 #Compile ADOL-C
-cd adolc_v220_issm
+cd adolc_issm
 
 autoreconf -f -i 
Index: /issm/trunk/externalpackages/adolc/install-update-dev.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install-update-dev.sh	(revision 13975)
+++ /issm/trunk/externalpackages/adolc/install-update-dev.sh	(revision 13975)
@@ -0,0 +1,26 @@
+#!/bin/bash
+set -eu
+
+#This script is very specific to the larour larsen nightly using adolc. 
+#It relies on just an update of adolc, and symlink to an existing adolc 
+#repo. 
+
+#Some cleanup
+rm -rf install adolc_issm
+
+#symlink: 
+ln -s  /u/astrid-r1b/larour/issm-uci/trunk-jpl/externalpackages/adolc/adolc_issm ./adolc_issm
+
+#update and compile
+cd adolc_issm
+git pull
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/adolc/install.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/install.sh	(revision 13974)
+++ 	(revision )
@@ -1,60 +1,0 @@
-#!/bin/bash
-set -eu
-
-#some issues on macosx64 with ISSM's autoconf. you might want to run native to mac on this.
-
-#Some cleanup
-rm -rf install ADOL-C-2.2.0 src trunk
-
-#Create install directories
-mkdir install src
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ADOL-C-2.2.0.tar.gz' 'ADOL-C-2.2.0.tar.gz'
-
-#Untar 
-tar -zxvf  ADOL-C-2.2.0.tar.gz
-
-#Move ADOL-C into install directory
-mv ADOL-C-2.2.0/* src
-rm -rf ADOL-C-2.2.0
-
-#Compile ADOL-C
-cd src 
-
-#export CC=gcc
-#export CXX=g++
-#export CFLAGS="-arch x86_64"
-#export CXXFLAGS="-arch x86_64"
-
-./configure \
-	--prefix=$ISSM_DIR/externalpackages/adolc/install \
-	--enable-sparse \
-	--enable-docexa \
-	--enable-addexa \
-	--disable-shave
-
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
-
-
-#Ok, bug with libtool: replace all LIBTOOL= by LIBTOOL=libtool 
-#in all Makefiles
-for i in `find ./ -name Makefile `
-do
-	echo $i
-	cat $i | sed 's/LIBTOOL =/LIBTOOL = libtool/g' > $i.bak 
-	mv $i.bak $i
-done
-
-#remake: 
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: /issm/trunk/externalpackages/adolc/update.sh
===================================================================
--- /issm/trunk/externalpackages/adolc/update.sh	(revision 13975)
+++ /issm/trunk/externalpackages/adolc/update.sh	(revision 13975)
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+cd adolc_issm
+git pull
+
+autoreconf -f -i 
+./configure --prefix=$ISSM_DIR/externalpackages/adolc/install 
+
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/android/android-ndk/install.sh
===================================================================
--- /issm/trunk/externalpackages/android/android-ndk/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/android/android-ndk/install.sh	(revision 13975)
@@ -1,4 +1,3 @@
 #!/bin/bash
-set -eu
 
 # This installs the Android NDK (Native Development Kit)
@@ -29,4 +28,4 @@
 # 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
+    $ANDROID_DIR/android-ndk/install/build/tools/make-standalone-toolchain.sh --platform=android-14 --install-dir=$ANDROID_DIR/android-ndk/install/arm-linux-android-install
 fi
Index: /issm/trunk/externalpackages/android/android-sdk/install.sh
===================================================================
--- /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/android/android-sdk/install.sh	(revision 13975)
@@ -1,4 +1,3 @@
 #!/bin/bash
-set -eu 
 
 # This installs the Android SDK (Software Development Kit)
Index: /issm/trunk/externalpackages/android/android_aux.sh
===================================================================
--- /issm/trunk/externalpackages/android/android_aux.sh	(revision 13974)
+++ /issm/trunk/externalpackages/android/android_aux.sh	(revision 13975)
@@ -16,5 +16,9 @@
 j=1;
 
+echo ""
+echo "This install script utilizes 'android_aux.sh' to allow for options."
+echo "For usage information enter: '--help'"
 echo Number of arguments is: $#
+
 for arg in $* 
 do 
@@ -22,9 +26,18 @@
         step=${BASH_REMATCH[1]}; 
         echo "Setting step to: " $step
-    elif [[ "$arg" =~ -j=([1-9]+[0-9]*) || "$arg" =~ ([1-9]+[0-9]*) ]]; then
+    elif [[ "$arg" == "--help" ]]; then
+        echo ""
+        echo "USAGE: $ install.sh [--step=#] [-j#]"
+        echo ""
+        echo "Where '#' is some integer."
+        echo "To check the number of steps check the install script."
+        echo ""
+        exit 1;
+    elif [[ "$arg" =~ -j=([1-9]+[0-9]*) ]]; then
         j=${BASH_REMATCH[1]}; 
         echo "Number of jobs set to: " $j
     else
         echo "Option not recognized"
+        exit 1;
     fi
 done
Index: /issm/trunk/externalpackages/chaco/install.sh
===================================================================
--- /issm/trunk/externalpackages/chaco/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/chaco/install.sh	(revision 13975)
@@ -10,4 +10,5 @@
 #Download from ISSM server
 $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Chaco-2.2.tar.gz' 'Chaco-2.2.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/chaco_guide.pdf' 'chaco_guide.pdf'
 
 # Untar 
Index: /issm/trunk/externalpackages/dakota/install-linux64-cloud.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-linux64-cloud.sh	(revision 13975)
+++ /issm/trunk/externalpackages/dakota/install-linux64-cloud.sh	(revision 13975)
@@ -0,0 +1,97 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src 
+rm -rf install 
+mkdir src install 
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_4_3.src.tar.gz' 'Dakota_4_3.src.tar.gz'
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/dakota/install" \
+	--without-graphics  \
+	--with-pic \
+	--disable-mpi \
+	--with-blas=/usr/lib/libblas.so \
+	--with-lapack=/usr/lib/liblapack.so
+cd ..
+
+#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
+#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
+#flag to the compilation.
+cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
+mv temp ./src/methods/NCSUOpt/Makefile
+
+cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/pebbl/src/Makefile
+
+cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-nappspack/Makefile
+
+cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-cddlib/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile 
+
+cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-conveyor/Makefile 
+
+cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-appspack/Makefile 
+
+cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/colin/src/Makefile
+
+cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/coliny/src/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile 
+
+cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/packages/ampl/Makefile 
+
+#Compile and install dakota
+cd src 
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk/externalpackages/dakota/install-pleiades-petsc3.3.sh
===================================================================
--- /issm/trunk/externalpackages/dakota/install-pleiades-petsc3.3.sh	(revision 13975)
+++ /issm/trunk/externalpackages/dakota/install-pleiades-petsc3.3.sh	(revision 13975)
@@ -0,0 +1,103 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf Dakota
+rm -rf src
+rm -rf install
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/Dakota_4_3.src.tar.gz' 'Dakota_4_3.src.tar.gz'
+
+#Untar 
+tar -zxvf  Dakota_4_3.src.tar.gz
+
+#Move Dakota to src directory
+mv Dakota/* src
+rm -rf Dakota
+
+#Apply patches
+patch src/src/ParallelLibrary.C ./ParallelLibrary.C.patch
+patch src/src/ParallelLibrary.H ./ParallelLibrary.H.patch
+patch src/src/NIDRProblemDescDB.C ./NIDRProblemDescDB.C.patch
+patch src/src/NonDSampling.C ./NonDSampling.C.patch
+patch src/src/NonDLocalReliability.C ./NonDLocalReliability.C.patch
+patch src/src/NonDUnilevelRBDO.C ./NonDUnilevelRBDO.C.patch    #  source not even used?
+#patch -R src/packages/Pecos/src/LHSDriver.cpp ./LHSDriver.cpp.patch
+
+#Configure dakota
+cd src
+./configure \
+--prefix="$ISSM_DIR/externalpackages/dakota/install/" \
+--without-graphics  \
+--with-pic \
+--disable-mpi \
+--with-blas="-L$ISSM_DIR/externalpackages/petsc/install/lib -lfblas " \
+--with-lapack="-L$ISSM_DIR/externalpackages/petsc/install/lib -lflapack "
+
+#--with-blas="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread" \
+#--with-lapack="-L/nasa/intel/mkl/10.0.011/lib/64/ -lmkl -lmkl_lapack -liomp5 -lpthread"
+#--with-blas="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack" \
+#--with-lapack="-L/nasa/intel/Compiler/11.1/046/mkl/lib/em64t/ -lmkl_intel_lp64 -lmkl_lapack"
+
+cd ..
+
+#Before compiling, if running on 64 bits, we need to active fPIC compilation. Some packages 
+#do not register -fPIC in Dakota, which is a problem. Edit the faulty Makefiles and add the -fPIC 
+#flag to the compilation.
+cat ./src/methods/NCSUOpt/Makefile | sed 's/FFLAGS = -g -O2/FFLAGS = -g -O2 -fPIC/g' >  temp
+mv temp ./src/methods/NCSUOpt/Makefile
+
+cat ./src/methods/acro/packages/pebbl/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/pebbl/src/Makefile
+
+cat ./src/methods/hopspack/src-nappspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-nappspack/Makefile
+
+cat ./src/methods/hopspack/src-cddlib/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-cddlib/Makefile
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile
+
+cat ./src/methods/hopspack/src-shared/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-shared/Makefile
+
+cat ./src/methods/hopspack/src-conveyor/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/methods/hopspack/src-conveyor/Makefile
+
+cat ./src/methods/hopspack/src-appspack/Makefile | sed 's/CXXFLAGS = -g -O2/CXXFLAGS = -g -O2  -fPIC/g' > temp
+mv temp ./src/methods/hopspack/src-appspack/Makefile
+
+cat ./src/methods/acro/packages/colin/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/colin/src/Makefile
+
+cat ./src/methods/acro/packages/coliny/src/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CXXFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp ./src/methods/acro/packages/coliny/src/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CFLAGS = -O2/CFLAGS = -O2 -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile
+
+cat ./src/methods/acro/packages/tpl/3po/Makefile | sed 's/CXXFLAGS = -O2 -fpermissive/CFLAGS = -O2 -fpermissive -fPIC/g' > temp
+mv temp  ./src/methods/acro/packages/tpl/3po/Makefile
+
+cat ./src/packages/ampl/Makefile | sed 's/CFLAGS = -g -O2/CFLAGS = -g -O2 -fPIC/g' > temp
+mv temp  ./src/packages/ampl/Makefile
+
+#Compile and install dakota
+cd src
+if [ $# -eq 0 ];
+then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
+fi
+cd ..
+
+#Weird behaviour of Dakota: libamplsolver.a and amplsolver.a are not the same thing!
+cd install/lib
+mv libamplsolver.a libamplsolver.a.bak
+ln -s ../../src/packages/ampl/amplsolver.a ./libamplsolver.a
Index: /issm/trunk/externalpackages/ec2ami/install.sh
===================================================================
--- /issm/trunk/externalpackages/ec2ami/install.sh	(revision 13975)
+++ /issm/trunk/externalpackages/ec2ami/install.sh	(revision 13975)
@@ -0,0 +1,12 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf ec2-api-tools.zip
+rm -rf ec2-api-tools-1.4.0.7
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ec2-api-tools.zip' 'ec2-api-tools.zip'
+
+#Untar 
+unzip ec2-api-tools.zip
Index: /issm/trunk/externalpackages/ec2api/install.sh
===================================================================
--- /issm/trunk/externalpackages/ec2api/install.sh	(revision 13975)
+++ /issm/trunk/externalpackages/ec2api/install.sh	(revision 13975)
@@ -0,0 +1,13 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf ec2-api-tools.zip
+rm -rf ec2-api-tools-1.6.3.1
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/ec2-api-tools.zip' 'ec2-api-tools.zip'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/ec2-ug.pdf' 'ec2-ug.pdf'
+
+#Untar 
+unzip ec2-api-tools.zip
Index: /issm/trunk/externalpackages/esmf/install.sh
===================================================================
--- /issm/trunk/externalpackages/esmf/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/esmf/install.sh	(revision 13975)
@@ -1,10 +1,4 @@
 #!/bin/bash
 set -eu
-
-#0: cleanup
-#1: install
-#2: test
-
-install=2
 
 export ESMF_DIR=$ISSM_DIR/externalpackages/esmf/esmf
@@ -12,40 +6,33 @@
 export ESMF_COMM=mpich2
 
-if [[ $install == "0" ]]; then
-	#Some cleanup
-	rm -rf esmf_5_2_0rp2
-	rm -rf esmf
+#Some cleanup
+rm -rf esmf_5_2_0rp2
+rm -rf esmf
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/esmf_5_2_0rp2_src.tar.gz' 'esmf_5_2_0rp2_src.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/ESMF_refdoc.pdf' 'ESMF_refdoc.pdf'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/ESMF_usrdoc.pdf' 'ESMF_usrdoc.pdf'
+
+#Untar 
+tar -zxvf  esmf_5_2_0rp2_src.tar.gz
+
+
+#Configure esmf
+cd esmf
+
+#Compile and install esmf
+if [ $# -eq 0 ]; then
+	make
+	make install
+else
+	make -j $1
+	make -j $1 install
 fi
 
-if [[ $install == "1" ]]; then
-
-	#Download from ISSM server
-	$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/esmf_5_2_0rp2_src.tar.gz' 'esmf_5_2_0rp2_src.tar.gz'
-
-	#Untar 
-	tar -zxvf  esmf_5_2_0rp2_src.tar.gz
-
-
-	#Configure esmf
-	cd esmf
-
-
-
-	#Compile and install esmf
-	if [ $# -eq 0 ]; then
-		make
-		make install
-	else
-		make -j $1
-		make -j $1 install
-	fi
+cd esmf
+if [ $# -eq 0 ]; then
+	make all_tests
+else
+	make -j $1 all_tests
 fi
-
-if [[ $install == "2" ]]; then
-	cd esmf
-	if [ $# -eq 0 ]; then
-		make all_tests
-	else
-		make -j $1 all_tests
-	fi
-fi
Index: /issm/trunk/externalpackages/gdal/GDALmake.opt.patch.astrid
===================================================================
--- /issm/trunk/externalpackages/gdal/GDALmake.opt.patch.astrid	(revision 13975)
+++ /issm/trunk/externalpackages/gdal/GDALmake.opt.patch.astrid	(revision 13975)
@@ -0,0 +1,8 @@
+31c31
+< LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib -lexpat -ljpeg -lz  -lm -lrt -ldl  $(KAK_LIBS) $(DWG_LIBS) $(CURL_LIB) \
+---
+> LIBS	=	$(SDE_LIB) -I/usr/include -lsqlite3 -L/usr/lib64 -lexpat -ljpeg -lz  -lm -lrt -ldl  $(KAK_LIBS) $(DWG_LIBS) $(CURL_LIB) \
+225c225
+< CURL_LIB	=	-L/usr/kerberos/lib64 -lcurl -ldl -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lidn -lssl -lcrypto -lz  
+---
+> CURL_LIB	=	-L/usr/lib64 -lcurl -ldl -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -lidn -lssl -lcrypto -lz  
Index: /issm/trunk/externalpackages/gdal/install-linux64-astrid.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-linux64-astrid.sh	(revision 13975)
+++ /issm/trunk/externalpackages/gdal/install-linux64-astrid.sh	(revision 13975)
@@ -0,0 +1,41 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.6.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.6.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.6.0/* src
+rm -rf gdal-1.6.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--without-python \
+	--without-png \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-ld-shared \
+	--with-unix-stdio-64=no \
+	--with-expat-lib=/usr/lib64/libexpat.so
+
+#Patch GDALmake.opt
+patch GDALmake.opt ../GDALmake.opt.patch.astrid
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/gdal/install-linux64-murdo.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-linux64-murdo.sh	(revision 13975)
+++ /issm/trunk/externalpackages/gdal/install-linux64-murdo.sh	(revision 13975)
@@ -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-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-macosx64.sh	(revision 13975)
+++ /issm/trunk/externalpackages/gdal/install-macosx64.sh	(revision 13975)
@@ -0,0 +1,38 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src
+rm -rf install
+rm -rf gdal-1.6.0
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
+
+#Untar 
+tar -zxvf  gdal-1.6.0.tar.gz
+
+#Move gdal into src directory
+mv gdal-1.6.0/* src
+rm -rf gdal-1.6.0
+
+#Configure gdal
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
+	--without-python \
+	--without-png \
+	--with-netcdf=no \
+	--with-jasper=no \
+	--without-ld-shared \
+	--with-unix-stdio-64=no \
+	--with-expat-lib=/usr/lib64/libexpat.so
+
+#Compile and install gdal
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: sm/trunk/externalpackages/gdal/install-murdo.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install-murdo.sh	(revision 13974)
+++ 	(revision )
@@ -1,39 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf src
-rm -rf install
-rm -rf gdal-1.6.0
-mkdir src install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
-
-#Untar 
-tar -zxvf  gdal-1.6.0.tar.gz
-
-#Move gdal into src directory
-mv gdal-1.6.0/* src
-rm -rf gdal-1.6.0
-
-#Configure gdal
-cd src
-./configure --prefix="$ISSM_DIR/externalpackages/gdal/install" \
-	--without-python \
-	--without-png \
-	--with-netcdf=no \
-	--with-jasper=no \
-	--without-ld-shared \
-	--with-unix-stdio-64=no 
-
-#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: sm/trunk/externalpackages/gdal/install.sh
===================================================================
--- /issm/trunk/externalpackages/gdal/install.sh	(revision 13974)
+++ 	(revision )
@@ -1,41 +1,0 @@
-#!/bin/bash
-set -eu
-
-#Some cleanup
-rm -rf src
-rm -rf install
-rm -rf gdal-1.6.0
-mkdir src install
-
-#Download from ISSM server
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gdal-1.6.0.tar.gz' 'gdal-1.6.0.tar.gz'
-
-#Untar 
-tar -zxvf  gdal-1.6.0.tar.gz
-
-#Move gdal into src directory
-mv gdal-1.6.0/* src
-rm -rf gdal-1.6.0
-
-#Configure gdal
-cd src
-./configure \
-	--prefix="$ISSM_DIR/externalpackages/gdal/install" \
-	--without-python \
-	--without-png \
-	--with-netcdf=no \
-	--with-jasper=no \
-	--without-ld-shared \
-	--with-unix-stdio-64=no \
-	--with-expat-lib=/usr/lib64/libexpat.so
-
-#Patch GDALmake.opt
-patch GDALmake.opt ../GDALmake.opt.patch
-
-#Compile and install gdal
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
-make install
Index: sm/trunk/externalpackages/git/install-nopython.sh
===================================================================
--- /issm/trunk/externalpackages/git/install-nopython.sh	(revision 13974)
+++ 	(revision )
@@ -1,23 +1,0 @@
-#!/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 13974)
+++ /issm/trunk/externalpackages/git/install.sh	(revision 13975)
@@ -18,5 +18,6 @@
 #install
 cd src 
-./configure  --prefix="$ISSM_DIR/externalpackages/git/install" --with-python="$ISSM_DIR/externalpackages/python/install/bin/python"
+./configure  --prefix="$ISSM_DIR/externalpackages/git/install"
+#--with-python="$ISSM_DIR/externalpackages/python/install/bin/python" #Do we really need this line?
 	
 #Compile
Index: /issm/trunk/externalpackages/gmp/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/gmp/install-linux64.sh	(revision 13975)
+++ /issm/trunk/externalpackages/gmp/install-linux64.sh	(revision 13975)
@@ -0,0 +1,29 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install gmp-5.0.5 
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/gmp-5.0.5.tar.bz2' 'gmp-5.0.5.tar.bz2'
+
+#Untar 
+bunzip2 gmp-5.0.5.tar.bz2
+tar -xvf  gmp-5.0.5.tar
+
+#Move gmp into install directory
+mv gmp-5.0.5/* src
+rm -rf gmp-5.0.5
+
+#install
+cd src 
+./configure --prefix="$ISSM_DIR/externalpackages/gmp/install" 
+
+#Compile and install gmp
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/gsl/install-android.sh
===================================================================
--- /issm/trunk/externalpackages/gsl/install-android.sh	(revision 13974)
+++ /issm/trunk/externalpackages/gsl/install-android.sh	(revision 13975)
@@ -24,6 +24,8 @@
 if [[ $step == "2" || $step == "0" ]]; then
     cd src
+
+    patch Makefile.am < Makefile.am.patch
     
-    autoreconf -iv --force -I $LIBTOOL_DIR/share/aclocal/ 
+    autoreconf -iv --force -I $ISSM_DIR/externalpackages/autotools/install/share/aclocal
 
     ./configure \
@@ -36,4 +38,5 @@
 #Compile gsl
 if [[ $step == "3" || $step == "0" ]]; then
+	cd src
     if [ $# -eq 0 ]; then
 	    make $j 
@@ -44,2 +47,3 @@
     make install
 fi
+
Index: /issm/trunk/externalpackages/hdf5/install.sh
===================================================================
--- /issm/trunk/externalpackages/hdf5/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/hdf5/install.sh	(revision 13975)
@@ -22,6 +22,7 @@
 if [ $# -eq 0 ]; then
 	make
+	make install
 else
 	make -j $1
+	make -j $1 install
 fi
-make install
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-altix64.sh	(revision 13975)
@@ -30,10 +30,6 @@
 patch -R ./src/include/mpicxx.h ../configs/1.0.2/altix64/mpicxx.h.patch
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
 
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-linux64.sh	(revision 13975)
@@ -30,9 +30,5 @@
 patch -R ./src/include/mpicxx.h ../configs/1.0.2/linux64/mpicxx.h.patch
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-macosx32.sh	(revision 13975)
@@ -29,10 +29,6 @@
 patch -R ./src/include/mpicxx.h ../configs/1.0.2/macosx32/mpicxx.h.patch
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
 
Index: /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.0.2-win32.sh	(revision 13975)
@@ -27,10 +27,6 @@
 patch -R ./src/include/mpicxx.h ../configs/1.0.2/win32/mpicxx.h.patch
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
 
Index: /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.3.1-linux64-berg.sh	(revision 13975)
@@ -36,13 +36,5 @@
 fi
 
-#Compile mpich2
-if [ $# -eq 0 ];
-then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 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 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-linux64.sh	(revision 13975)
@@ -26,9 +26,5 @@
 	--enable-f91=gfortran 
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-macosx32.sh	(revision 13975)
@@ -28,9 +28,5 @@
 	--enable-fc
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 13974)
+++ /issm/trunk/externalpackages/mpich2/install-1.4-macosx64.sh	(revision 13975)
@@ -28,9 +28,5 @@
 	--enable-fc
 
-#Compile mpich2
-if [ $# -eq 0 ]; then
-	make
-else
-	make -j $1
-fi
+#Compile mpich2 (parallel make not supported)
+make
 make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.5-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.5-linux64.sh	(revision 13975)
+++ /issm/trunk/externalpackages/mpich2/install-1.5-linux64.sh	(revision 13975)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich2/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.5-macosx64.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.5-macosx64.sh	(revision 13975)
+++ /issm/trunk/externalpackages/mpich2/install-1.5-macosx64.sh	(revision 13975)
@@ -0,0 +1,32 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich2/install" \
+	--enable-shared \
+	--enable-sharedlibs=gcc \
+	--enable-f91=gfortran 
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: /issm/trunk/externalpackages/mpich2/install-1.5-walgreen.sh
===================================================================
--- /issm/trunk/externalpackages/mpich2/install-1.5-walgreen.sh	(revision 13975)
+++ /issm/trunk/externalpackages/mpich2/install-1.5-walgreen.sh	(revision 13975)
@@ -0,0 +1,34 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf src install mpich2-1.5
+mkdir src install
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/mpich2-1.5.tar.gz' 'mpich2-1.5.tar.gz'
+
+#Untar 
+tar -zxvf  mpich2-1.5.tar.gz
+
+#Move mpich2 into src directory
+mv mpich2-1.5/* src
+rm -rf mpich2-1.5
+
+#Configure mpich2
+cd src
+./configure \
+	--prefix="$ISSM_DIR/externalpackages/mpich2/install" \
+	--enable-shared \
+	--with-device=ch3:sock\
+	--with-atomic-primitives=no
+
+	#--with-device=ch_p4 \
+
+#Compile mpich2 (this new version supports parallel make)
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install 
Index: sm/trunk/externalpackages/netcdf/install-4.0.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install-4.0.sh	(revision 13974)
+++ 	(revision )
@@ -1,27 +1,0 @@
-#!/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: sm/trunk/externalpackages/netcdf/install-4.2.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install-4.2.sh	(revision 13974)
+++ 	(revision )
@@ -1,30 +1,0 @@
-#!/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: /issm/trunk/externalpackages/netcdf/install.sh
===================================================================
--- /issm/trunk/externalpackages/netcdf/install.sh	(revision 13975)
+++ /issm/trunk/externalpackages/netcdf/install.sh	(revision 13975)
@@ -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: /issm/trunk/externalpackages/numpy/install-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-linux64.sh	(revision 13974)
+++ /issm/trunk/externalpackages/numpy/install-linux64.sh	(revision 13975)
@@ -10,11 +10,14 @@
 #clean up
 rm -rf numpy
+rm -rf numpy-1.7.0b2
 
 #download numpy first
-export GIT_SSL_NO_VERIFY=true 
-git clone https://github.com/numpy/numpy.git
+#export GIT_SSL_NO_VERIFY=true 
+#git clone https://github.com/numpy/numpy.git
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/numpy-1.7.0b2.tar.gz' 'numpy-1.7.0b2.tar.gz'
 
 #install numpy
-cd numpy
+tar -zxvf numpy-1.7.0b2.tar.gz
+cd numpy-1.7.0b2
 python setup.py build
 python setup.py install
Index: /issm/trunk/externalpackages/numpy/install-macosx-lion.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-macosx-lion.sh	(revision 13974)
+++ /issm/trunk/externalpackages/numpy/install-macosx-lion.sh	(revision 13975)
@@ -6,9 +6,19 @@
 export FFLAGS=-ff2c
 
+#clean up
+rm -rf numpy
+rm -rf numpy-1.7.0b2
+
 #download numpy first
-git clone https://github.com/numpy/numpy.git
+#export GIT_SSL_NO_VERIFY=true 
+#git clone https://github.com/numpy/numpy.git
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/numpy-1.7.0b2.tar.gz' 'numpy-1.7.0b2.tar.gz'
 
 #install numpy
-cd numpy
+tar -zxvf numpy-1.7.0b2.tar.gz
+cd numpy-1.7.0b2
 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-mlion.sh
===================================================================
--- /issm/trunk/externalpackages/numpy/install-macosx-mlion.sh	(revision 13975)
+++ /issm/trunk/externalpackages/numpy/install-macosx-mlion.sh	(revision 13975)
@@ -0,0 +1,24 @@
+#!/bin/bash
+set -eu
+
+export CC=gcc
+export CXX=g++
+export FFLAGS=-ff2c
+
+#clean up
+rm -rf numpy
+rm -rf numpy-1.7.0b2
+
+#download numpy first
+#export GIT_SSL_NO_VERIFY=true 
+#git clone https://github.com/numpy/numpy.git
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/numpy-1.7.0b2.tar.gz' 'numpy-1.7.0b2.tar.gz'
+
+#install numpy
+tar -zxvf numpy-1.7.0b2.tar.gz
+cd numpy-1.7.0b2
+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/openssl/install.sh
===================================================================
--- /issm/trunk/externalpackages/openssl/install.sh	(revision 13975)
+++ /issm/trunk/externalpackages/openssl/install.sh	(revision 13975)
@@ -0,0 +1,23 @@
+#!/bin/bash
+set -eu
+
+#Some cleanup
+rm -rf install src
+
+#Download latest version
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/openssl-0.9.8x.tar.gz' 'openssl-0.9.8x.tar.gz'
+
+#Untar
+tar -xzf openssl-0.9.8x.tar.gz
+mv openssl-0.9.8x src
+mkdir install
+
+#Configure openssl
+cd src
+./config --prefix="$ISSM_DIR/externalpackages/openssl/install"
+if [ $# -eq 0 ]; then
+	make
+else
+	make -j $1
+fi
+make install
Index: /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 13974)
+++ /issm/trunk/externalpackages/petsc/install-3.2-greenplanet.sh	(revision 13975)
@@ -22,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=/sopt/mpi/openmpi-1.5.4_psm/intel/ \
Index: /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh	(revision 13975)
+++ /issm/trunk/externalpackages/petsc/install-3.3-pleiades.sh	(revision 13975)
@@ -0,0 +1,66 @@
+#!/bin/bash
+
+#Some cleanup
+rm -rf install petsc-3.3-p2 src
+mkdir install src
+
+#Download from ISSM server
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
+
+#Untar and move petsc to install directory
+tar -zxvf  petsc-3.3-p2.tar.gz
+mv petsc-3.3-p2/* src/
+rm -rf petsc-3.3-p2
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --with-batch=1  \
+ --PETSC_ARCH="$ISSM_ARCH" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --with-mpi-lib=/nasa/sgi/mpt/2.06a67/lib/libmpi.so \
+ --with-mpi-include=/nasa/sgi/mpt/2.06a67/include  \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-mumps=yes \
+ --download-scalapack=yes \
+ --download-blacs=yes \
+ --download-plapack=no \
+ --download-metis=yes \
+ --download-parmetis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-hypre=yes \
+ --with-cxx=icc \
+ --with-fc=ifort \
+ --COPTFLAGS="-lmpi -O3" \
+ --FOPTFLAGS="-lmpi -O3" \
+ --CXXOPTFLAGS="-lmpi -O3"
+
+#prepare script to reconfigure petsc
+cat > script.queue << EOF
+#PBS -S /bin/bash
+#PBS -l select=1:ncpus=1:model=wes 
+#PBS -l walltime=200 
+#PBS -W group_list=s1010
+#PBS -m e 
+
+. /usr/share/modules/init/bash 
+module load comp-intel/2012.0.032 
+module load mpi-sgi/mpt.2.06a67  
+module load math/intel_mkl_64_10.0.011
+
+export PATH="$PATH:." 
+export MPI_GROUP_MAX=64 
+mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
+EOF
+
+#print instructions
+echo "== Now: cd src/ "
+echo "== qsub -q devel script.queue "
+echo "== Then run reconfigure script generated by PETSc and follow instructions"
Index: /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh	(revision 13975)
+++ /issm/trunk/externalpackages/petsc/install-3.3-walgreen.sh	(revision 13975)
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+##Some cleanup
+#rm -rf install petsc-3.3-p2 src
+#mkdir install src
+#
+##Download from ISSM server
+#$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/petsc-lite-3.3-p2.tar.gz' 'petsc-3.3-p2.tar.gz'
+#
+##Untar and move petsc to install directory
+#tar -zxvf  petsc-3.3-p2.tar.gz
+#mv petsc-3.3-p2/* src/
+#rm -rf petsc-3.3-p2
+
+#configure
+cd src
+./config/configure.py \
+ --prefix="$ISSM_DIR/externalpackages/petsc/install" \
+ --PETSC_DIR="$ISSM_DIR/externalpackages/petsc/src" \
+ --with-debugging=0 \
+ --with-shared-libraries=1 \
+ --with-blas-lapack-dir=/opt/intel/mkl/10.0.1.014/ \
+ --known-mpi-shared-libraries=1 \
+ --with-mpi=1 \
+ --download-mumps=yes \
+ --download-blacs=yes  \
+ --download-blas=yes \
+ --download-f-blas-lapack=yes \
+ --download-parmetis=yes \
+ --download-metis=yes \
+ --download-trilinos=yes \
+ --download-euclid=yes \
+ --download-spai=yes \
+ --download-superlu=yes \
+ --download-hypre=yes \
+ --download-prometheus=yes \
+ --with-cc=/opt/mpich/ch-p4/bin/mpicc \
+ --with-cxx=/opt/mpich/ch-p4/bin/mpicxx \
+ --with-fc=/opt/mpich/ch-p4/bin/mpif90 \
+ --COPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" \
+ --FOPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" \
+ --CXXOPTFLAGS="-I/opt/mpich/ch-p4/include/ -lmpich -O3" 
Index: /issm/trunk/externalpackages/petsc/install-dev-linux64.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 13974)
+++ /issm/trunk/externalpackages/petsc/install-dev-linux64.sh	(revision 13975)
@@ -1,4 +1,3 @@
 #!/bin/bash
-set -eu
 
 STEP=2
@@ -19,9 +18,12 @@
 #      hg pull -u
 
-
 # configure script
-# Note: using metis from externalpackages did not work...
-#       -for now download new metis
-#       -rename metis in externalpackages to metis2
+# Note: 
+#  Metis: -using metis from externalpackages did not work...
+#         -for now download new metis
+#         -rename metis in externalpackages to metis2
+#
+# SuperLU: -If download-..-=yes does not work try downloading from
+#    --download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
 
 
@@ -38,5 +40,4 @@
 	--with-shared-libraries=1 \
 	--download-mumps=yes \
-	--download-plapack=yes \
 	--download-scalapack=yes \
 	--download-blacs=yes  \
@@ -47,12 +48,10 @@
 	--download-trilinos=yes \
 	--download-euclid=yes \
-	--download-pastix=yes \
-	--download-ptscotch=yes \
 	--download-spooles=yes \
 	--download-spai=yes \
-	--download-superlu=yes \
+	--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
 	--download-hypre=yes \
-	--download-prometheus=yes \
-	--with-pic=1
+	--download-c2html=yes
+#	--with-pic=1
 
 	#Compile petsc and install it
Index: /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh
===================================================================
--- /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh	(revision 13974)
+++ /issm/trunk/externalpackages/petsc/install-dev-pleiades.sh	(revision 13975)
@@ -1,7 +1,6 @@
 #!/bin/bash
-set -eu
 #Step 0: download
 #Step 1: install and write script
-STEP=0
+STEP=1
 
 if [ $STEP -eq 0 ]; then
@@ -24,7 +23,10 @@
 # for now downloading new metis
 #   -then rename metis in externalpackages to metis2
+#
+#		--download-prometheus=yes \
+#--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
+#		--download-plapack=yes \
+
 if [ $STEP -eq 1 ]; then
-
-	mkdir install
 
 	#configure
@@ -36,11 +38,9 @@
 		--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 \
-		--with-mpi-lib=/nasa/sgi/mpt/2.04/lib/libmpi.so \
-		--with-mpi-include=/nasa/sgi/mpt/2.04/include  \
+		--with-mpi=1 \
 		--download-mumps=yes \
-		--download-plapack=yes \
 		--download-scalapack=yes \
 		--download-blacs=yes  \
@@ -51,29 +51,21 @@
 		--download-trilinos=yes \
 		--download-euclid=yes \
-		--download-pastix=yes \
-		--download-ptscotch=yes \
-		--download-spooles=yes \
 		--download-spai=yes \
-		--download-superlu=yes \
+		--download-superlu=http://crd.lbl.gov/~xiaoye/SuperLU/superlu_4.3.tar.gz \
 		--download-hypre=yes \
-		--download-prometheus=yes \
-		--FFLAGS=-I/usr/include \
-		--with-cxx=icpc \
-		--with-cc=icc \
-		--with-fc=ifort \
-		--COPTFLAGS=" -O3 -xS" \
-		--FOPTFLAGS=" -O3 -xS" \
-		--CXXOPTFLAGS=" -O3 -xS" \
-		--with-pic=1
+		--with-cxx=/nasa/sgi/mpt/2.06a67/bin/mpicxx \
+		--with-fc=/nasa/sgi/mpt/2.06a67/bin/mpif90 \
+		--COPTFLAGS="-lmpi -O3" \
+		--FOPTFLAGS="-lmpi -O3" \
+		--CXXOPTFLAGS="-lmpi -O3" 
 		cat > script.queue << EOF
 #PBS -S /bin/bash
-#PBS -q debug 
-#PBS -l select=1:ncpus=1:model=har 
+#PBS -l select=1:ncpus=1:model=wes 
 #PBS -l walltime=200 
 #PBS -W group_list=s1010 
 #PBS -m e 
 . /usr/share/modules/init/bash 
-module load comp-intel/11.1.046 
-module load mpi-sgi/mpt.2.04  #DEFINES MPI_Type_create_indexed_block
+module load comp-intel/2012.0.032 
+module load mpi-sgi/mpt.2.06a67  
 module load math/intel_mkl_64_10.0.011 
 export PATH="$PATH:." 
@@ -81,4 +73,6 @@
 mpiexec -np 1 ./conftest-linux-gnu-ia64-intel.py
 EOF
-	echo "== Follow PETSc's instructions"
+	echo "== Now: cd src/ "
+	echo "== qsub -q devel script.queue "
+	echo "== Then run reconfigure script generated by PETSc and follow instructions"
 fi
Index: /issm/trunk/externalpackages/python/install-2.7.3-macosx-mlion.sh
===================================================================
--- /issm/trunk/externalpackages/python/install-2.7.3-macosx-mlion.sh	(revision 13975)
+++ /issm/trunk/externalpackages/python/install-2.7.3-macosx-mlion.sh	(revision 13975)
@@ -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/readline/install.sh
===================================================================
--- /issm/trunk/externalpackages/readline/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/readline/install.sh	(revision 13975)
@@ -17,5 +17,5 @@
 rm -rf readline-6.2.2
 
-$install
+#install
 cd src
 python setup.py install
Index: /issm/trunk/externalpackages/scipy/install-macosx-mlion.sh
===================================================================
--- /issm/trunk/externalpackages/scipy/install-macosx-mlion.sh	(revision 13975)
+++ /issm/trunk/externalpackages/scipy/install-macosx-mlion.sh	(revision 13975)
@@ -0,0 +1,20 @@
+#!/bin/bash
+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
+
+#install scipy
+python setup.py build
+python setup.py install
Index: /issm/trunk/externalpackages/scotch/install.sh
===================================================================
--- /issm/trunk/externalpackages/scotch/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/scotch/install.sh	(revision 13975)
@@ -12,4 +12,6 @@
 #Download from ISSM server
 $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/scotch_5.1.6.tar.gz' 'scotch_5.1.6.tar.gz'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/ptscotch_user5.1.pdf' 'ptscotch_user5.1.pdf'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/scotch_user5.1.pdf' 'scotch_user5.1.pdf'
 
 # Untar 
Index: /issm/trunk/externalpackages/shapelib/install.sh
===================================================================
--- /issm/trunk/externalpackages/shapelib/install.sh	(revision 13974)
+++ /issm/trunk/externalpackages/shapelib/install.sh	(revision 13975)
@@ -10,5 +10,6 @@
 #Download from ISSM server
 $ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/shapelib-1.2.10.tar.gz' 'shapelib-1.2.10.tar.gz'
-$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/shape_eg_data.zip' 'shape_eg_data.zip'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/shape_eg_data.zip'  'shape_eg_data.zip'
+$ISSM_DIR/scripts/DownloadExternalPackage.py 'http://issm.jpl.nasa.gov/files/externalpackages/docs/shapefile.pdf' 'shapefile.pdf'
 
 # Untar 
Index: /issm/trunk/externalpackages/starcluster/install.sh
===================================================================
--- /issm/trunk/externalpackages/starcluster/install.sh	(revision 13975)
+++ /issm/trunk/externalpackages/starcluster/install.sh	(revision 13975)
@@ -0,0 +1,7 @@
+#/bin/bash
+
+git clone git://github.com/jtriley/StarCluster.git
+
+cd StarCluster
+python distribute_setup.py
+python setup.py install
Index: /issm/trunk/externalpackages/vim/addons/vim/colors/issm_black.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 13974)
+++ /issm/trunk/externalpackages/vim/addons/vim/colors/issm_black.vim	(revision 13975)
@@ -1,227 +1,86 @@
-" ir_black color scheme
-" More at: http://blog.infinitered.com/entries/show/8
+" issm_black color scheme
+" table http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
 
-
-" ********************************************************************************
-" Standard colors used in all ir_black themes:
-" Note, x:x:x are RGB values
-"
-"  normal: #f6f3e8
-" 
-"  string: #A8FF60  168:255:96                   
-"    string inner (punc, code, etc): #00A0A0  0:160:160
-"  number: #FF73FD  255:115:253                 
-"  comments: #7C7C7C  124:124:124
-"  keywords: #96CBFE  150:203:254             
-"  operators: white
-"  class: #FFFFB6  255:255:182
-"  method declaration name: #FFD2A7  255:210:167
-"  regular expression: #E9C062  233:192:98
-"    regexp alternate: #FF8000  255:128:0
-"    regexp alternate 2: #B18A3D  177:138:61
-"  variable: #C6C5FE  198:197:254
-"  
-" Misc colors:
-"  red color (used for whatever): #FF6C60   255:108:96 
-"     light red: #FFB6B0   255:182:176
-"
-"  brown: #E18964  good for special
-"
-"  lightpurpleish: #FFCCFF
-" 
-" Interface colors:
-"  background color: black
-"  cursor (where underscore is used): #FFA560  255:165:96
-"  cursor (where block is used): white
-"  visual selection: #1D1E2C  
-"  current line: #151515  21:21:21
-"  search selection: #07281C  7:40:28
-"  line number: #3D3D3D  61:61:61
-
-
-" ********************************************************************************
-" The following are the preferred 16 colors for your terminal
-"           Colors      Bright Colors
-" Black     #4E4E4E     #7C7C7C
-" Red       #FF6C60     #FFB6B0
-" Green     #A8FF60     #CEFFAB
-" Yellow    #FFFFB6     #FFFFCB
-" Blue      #96CBFE     #FFFFCB
-" Magenta   #FF73FD     #FF9CFE
-" Cyan      #C6C5FE     #DFDFFE
-" White     #EEEEEE     #FFFFFF
-
-
-" ********************************************************************************
+"Set up coloring
 hi clear
-
 if exists("syntax_on")
   syntax reset
 endif
 syntax on
-
 let colors_name = "issm_black"
 
-"                   GUI not used in terminal mode                     forground           background          style (reverse,bold,..)
-"hi Example         guifg=NONE        guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE
+"preferred colors:
+"  0  : black
+"  9  : red
+" 15  : white
+" 69  : blue
+" 87  : cyan
+" 129 : dark purple
+" 202 : orange
+" 214 : light orange
+" 227 : yellow
+" 234 : very dark gray
+" 241 : dark gray
+" 244 : gray
+" 255 : light gray
 
+"                forground    background   style (reverse,bold,..)
 " General colors
-hi Normal           guifg=#f6f3e8     guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-hi NonText          guifg=#070707     guibg=black       gui=NONE      ctermfg=129        ctermbg=NONE        cterm=NONE         "214 =orange
-
-hi Cursor           guifg=black       guibg=white       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse      "cursor (mouse)
-hi LineNr           guifg=#3D3D3D     guibg=black       gui=NONE      ctermfg=249        ctermbg=232         cterm=NONE         "line numbering gray/blak 
-
-hi VertSplit        guifg=#202020     guibg=#202020     gui=NONE      ctermfg=241        ctermbg=241         cterm=NONE         "vertical split
-hi StatusLine       guifg=#CCCCCC     guibg=#202020     gui=italic    ctermfg=241        ctermbg=87          cterm=NONE         "87 = cyan
-hi StatusLineNC     guifg=black       guibg=#202020     gui=NONE      ctermfg=87         ctermbg=241         cterm=NONE         "241 = dark gray
-
-hi Folded           guifg=#a0a8b0     guibg=#384048     gui=NONE      ctermfg=135        ctermbg=234         cterm=NONE         "folded 129 = violet ,234 Gray
-hi Title            guifg=#f6f3e8     guibg=NONE        gui=bold      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-hi Visual           guifg=NONE        guibg=#262D51     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse "visual 255 = white
-
-hi SpecialKey       guifg=#808080     guibg=#343434     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-
-hi WildMenu         guifg=green       guibg=yellow      gui=NONE      ctermfg=black      ctermbg=yellow      cterm=NONE          "?????
-hi PmenuSbar        guifg=black       guibg=white       gui=NONE      ctermfg=black      ctermbg=magenta     cterm=NONE          "????
-"hi Ignore           guifg=gray        guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-
-hi Error            guifg=white        guibg=NONE        gui=none ctermfg=255      ctermbg=129         cterm=NONE
-hi ErrorMsg         guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=129         cterm=NONE                   " 196 = red
-hi WarningMsg       guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=201         cterm=NONE                   "201 = magenta
+hi Normal        ctermfg=NONE ctermbg=NONE cterm=NONE
+hi NonText       ctermfg=129  ctermbg=NONE cterm=NONE
+hi Cursor        ctermfg=NONE ctermbg=NONE cterm=reverse
+hi LineNr        ctermfg=15   ctermbg=241  cterm=NONE
+hi VertSplit     ctermfg=241  ctermbg=241  cterm=NONE
+hi StatusLine    ctermfg=241  ctermbg=87   cterm=NONE
+hi StatusLineNC  ctermfg=87   ctermbg=241  cterm=NONE
+hi Folded        ctermfg=141  ctermbg=236  cterm=NONE
+hi Title         ctermfg=NONE ctermbg=NONE cterm=NONE
+hi Visual        ctermfg=NONE ctermbg=NONE cterm=reverse
+hi SpecialKey    ctermfg=NONE ctermbg=NONE cterm=NONE
+hi WildMenu      ctermfg=0    ctermbg=227  cterm=NONE
+hi PmenuSbar     ctermfg=0    ctermbg=129  cterm=NONE
+hi Error         ctermfg=15   ctermbg=129  cterm=NONE
+hi ErrorMsg      ctermfg=15   ctermbg=129  cterm=NONE
+hi WarningMsg    ctermfg=15   ctermbg=129  cterm=NONE
 
 " Message displayed in lower left, such as --INSERT--
-hi ModeMsg          guifg=black       guibg=#C6C5FE     gui=BOLD      ctermfg=241      ctermbg=87        cterm=BOLD
-
+hi ModeMsg       ctermfg=0  ctermbg=87   cterm=BOLD
 if version >= 700 " Vim 7.x specific colors
-  hi CursorLine     guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
-  hi CursorColumn   guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
-  hi MatchParen     guifg=#f6f3e8     guibg=#857b6f     gui=BOLD      ctermfg=87         ctermbg=241         cterm=BOLD,reverse  "matching parenthesis
-  hi Pmenu          guifg=#f6f3e8     guibg=#444444     gui=NONE      ctermfg=black      ctermbg=white         cterm=NONE "auto completion panel
-  hi PmenuSel       guifg=#000000     guibg=#cae682     gui=NONE      ctermfg=255        ctermbg=darkgray    cterm=NONE
-  hi Search         guifg=NONE        guibg=NONE        gui=underline ctermfg=black      ctermbg=220         cterm=NONE  "227 = yellow
+  hi CursorLine   ctermfg=NONE ctermbg=NONE cterm=BOLD
+  hi CursorColumn ctermfg=NONE ctermbg=NONE cterm=BOLD
+  hi MatchParen   ctermfg=87   ctermbg=241  cterm=reverse "matching parenthesis
+  hi Pmenu        ctermfg=0    ctermbg=15   cterm=NONE    "auto completion panel
+  hi PmenuSel     ctermfg=255  ctermbg=241  cterm=NONE
+  hi Search       ctermfg=0    ctermbg=220  cterm=NONE
 endif
 
 " Syntax highlighting
-hi Comment          guifg=#7C7C7C     guibg=NONE        gui=NONE      ctermfg=243         ctermbg=NONE        cterm=NONE
-hi String           guifg=#A8FF60     guibg=NONE        gui=NONE      ctermfg=120         ctermbg=NONE        cterm=NONE
-hi Number           guifg=#FF73FD     guibg=NONE        gui=NONE      ctermfg=201         ctermbg=NONE        cterm=NONE
+hi Comment      ctermfg=244  ctermbg=NONE cterm=NONE
+hi String       ctermfg=120  ctermbg=NONE cterm=NONE
+hi Number       ctermfg=201  ctermbg=NONE cterm=NONE
+hi Keyword      ctermfg=9    ctermbg=NONE cterm=NONE  " matlab function
+hi PreProc      ctermfg=9    ctermbg=NONE cterm=NONE  " def undef include
+hi Conditional  ctermfg=220  ctermbg=NONE cterm=NONE  " if else end
+hi Todo         ctermfg=214  ctermbg=NONE cterm=NONE
+hi Constant     ctermfg=196  ctermbg=NONE cterm=NONE
+hi Identifier   ctermfg=9    ctermbg=NONE cterm=NONE
+hi Function     ctermfg=69   ctermbg=NONE cterm=NONE "functions 69 = pastel blue
+hi Type         ctermfg=87   ctermbg=NONE cterm=NONE "cterm matlab global
+hi Statement    ctermfg=69   ctermbg=NONE cterm=NONE "cd ls sed mv
+hi Special      ctermfg=202  ctermbg=NONE cterm=NONE " matlab '...'
+hi Delimiter    ctermfg=NONE ctermbg=NONE cterm=NONE " [ ]
+hi Operator     ctermfg=202  ctermbg=NONE cterm=NONE " == &
+hi Directory    ctermfg=87   ctermbg=NONE cterm=NONE " == & 
 
-hi Keyword          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE  " matlab function
-hi PreProc          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE   " def undef include
-hi Conditional      guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=220         ctermbg=NONE        cterm=NONE  " if else end
-
-hi Todo             guifg=#8f8f8f     guibg=NONE        gui=NONE      ctermfg=214          ctermbg=NONE        cterm=NONE
-hi Constant         guifg=#99CC99     guibg=NONE        gui=NONE      ctermfg=196         ctermbg=NONE        cterm=NONE
-
-hi Identifier       guifg=#C6C5FE     guibg=NONE        gui=NONE      ctermfg=red         ctermbg=NONE        cterm=NONE
-hi Function         guifg=#FFD2A7     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE "functions 69 = pastel blue
-hi Type             guifg=#FFFFB6     guibg=NONE        gui=NONE      ctermfg=87         ctermbg=NONE        cterm=NONE "cterm matlab global
-hi Statement        guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE " cd ls sed mv
-
-hi Special          guifg=#E18964     guibg=NONE        gui=NONE      ctermfg=202         ctermbg=NONE        cterm=NONE  " ; 202  = orange 
-hi Delimiter        guifg=#00A0A0     guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE  " [ ]
-hi Operator         guifg=white       guibg=NONE        gui=NONE      ctermfg=202         ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
-
-hi Directory        guifg=white       guibg=NONE        gui=NONE      ctermfg=87          ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
-
- "Specific for diff
- hi DiffAdd      guifg=#ffff33 guibg=#404010 gui=bold term=none cterm=none ctermfg=black ctermbg=119
- hi DiffChange                 guibg=#202020 gui=bold term=none cterm=none ctermfg=black ctermbg=228
- hi DiffText     guifg=#3333ff guibg=#100040 gui=bold term=none cterm=none ctermfg=black ctermbg=178
- hi DiffDelete   guifg=#ff0000 guibg=#401010 gui=bold term=none cterm=none ctermfg=black ctermbg=197
- hi diffLine     guifg=#444444 guibg=bg gui=bold term=none cterm=bold ctermfg=darkgrey
- hi diffOldLine  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
- hi diffOldFile  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
- hi diffNewFile  guifg=#444444 guibg=bg gui=none term=none cterm=none ctermfg=darkgrey
- hi diffAdded    guifg=#80ff80 guibg=bg gui=none term=none cterm=none
- hi diffRemoved  guifg=#ff0000 guibg=bg gui=none term=none cterm=none ctermfg=red
- hi diffChanged  guifg=#0000ff guibg=bg gui=none term=none cterm=none ctermfg=blue
-
-hi link Character       Constant
-hi link Boolean         Constant
-hi link Float           Number
-hi link Repeat          Statement
-hi link Label           Statement
-hi link Exception       Statement
-hi link Include         PreProc
-hi link Define          PreProc
-hi link Macro           PreProc
-hi link PreCondit       PreProc
-hi link StorageClass    Type
-hi link Structure       Type
-hi link Typedef         Type
-hi link Tag             Special
-hi link SpecialChar     Special
-hi link SpecialComment  Special
-hi link Debug           Special
-
-
-" Special for Ruby
-hi rubyRegexp                  guifg=#B18A3D      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
-hi rubyRegexpDelimiter         guifg=#FF8000      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
-hi rubyEscape                  guifg=white        guibg=NONE      gui=NONE      ctermfg=cyan           ctermbg=NONE      cterm=NONE
-hi rubyInterpolationDelimiter  guifg=#00A0A0      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE
-hi rubyControl                 guifg=#6699CC      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE  "and break, etc
-"hi rubyGlobalVariable          guifg=#FFCCFF      guibg=NONE      gui=NONE      ctermfg=lightblue      ctermbg=NONE      cterm=NONE  "yield
-hi rubyStringDelimiter         guifg=#336633      guibg=NONE      gui=NONE      ctermfg=lightgreen     ctermbg=NONE      cterm=NONE
-"rubyInclude
-"rubySharpBang
-"rubyAccess
-"rubyPredefinedVariable
-"rubyBoolean
-"rubyClassVariable
-"rubyBeginEnd
-"rubyRepeatModifier
-"hi link rubyArrayDelimiter    Special  " [ , , ]
-"rubyCurlyBlock  { , , }
-
-hi link rubyClass             Keyword 
-hi link rubyModule            Keyword 
-hi link rubyKeyword           Keyword 
-hi link rubyOperator          Operator
-hi link rubyIdentifier        Identifier
-hi link rubyInstanceVariable  Identifier
-hi link rubyGlobalVariable    Identifier
-hi link rubyClassVariable     Identifier
-hi link rubyConstant          Type  
-
-
-" Special for Java
-" hi link javaClassDecl    Type
-hi link javaScopeDecl         Identifier 
-hi link javaCommentTitle      javaDocSeeTag 
-hi link javaDocTags           javaDocSeeTag 
-hi link javaDocParam          javaDocSeeTag 
-hi link javaDocSeeTagParam    javaDocSeeTag 
-
-hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
-hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
-"hi javaClassDecl              guifg=#CCFFCC     guibg=NONE        gui=NONE      ctermfg=white       ctermbg=NONE        cterm=NONE
-
-
-" Special for XML
-hi link xmlTag          Keyword 
-hi link xmlTagName      Conditional 
-hi link xmlEndTag       Identifier 
-
-
-" Special for HTML
-hi link htmlTag         Keyword 
-hi link htmlTagName     Conditional 
-hi link htmlEndTag      Identifier 
-
-
-" Special for Javascript
-hi link javaScriptNumber      Number 
-
-
-" Special for Python
-"hi  link pythonEscape         Keyword      
-
-
-" Special for CSharp
-hi  link csXmlTag             Keyword      
-
-
-" Special for PHP
+"Specific for diff
+hi DiffAdd      cterm=none ctermfg=0 ctermbg=119
+hi DiffChange   cterm=none ctermfg=0 ctermbg=228
+hi DiffText     cterm=none ctermfg=0 ctermbg=178
+hi DiffDelete   cterm=none ctermfg=0 ctermbg=197
+hi diffLine     cterm=bold ctermfg=241
+hi diffOldLine  cterm=none ctermfg=241
+hi diffOldFile  cterm=none ctermfg=241
+hi diffNewFile  cterm=none ctermfg=241
+hi diffAdded    cterm=none
+hi diffRemoved  cterm=none ctermfg=9
+hi diffChanged  cterm=none ctermfg=69
Index: /issm/trunk/externalpackages/vim/addons/vim/colors/issm_white.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 13974)
+++ /issm/trunk/externalpackages/vim/addons/vim/colors/issm_white.vim	(revision 13975)
@@ -1,212 +1,86 @@
-" ir_black color scheme
-" More at: http://blog.infinitered.com/entries/show/8
+" issm_white scheme
+" table http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
 
-
-" ********************************************************************************
-" Standard colors used in all ir_black themes:
-" Note, x:x:x are RGB values
-"
-"  normal: #f6f3e8
-" 
-"  string: #A8FF60  168:255:96                   
-"    string inner (punc, code, etc): #00A0A0  0:160:160
-"  number: #FF73FD  255:115:253                 
-"  comments: #7C7C7C  124:124:124
-"  keywords: #96CBFE  150:203:254             
-"  operators: white
-"  class: #FFFFB6  255:255:182
-"  method declaration name: #FFD2A7  255:210:167
-"  regular expression: #E9C062  233:192:98
-"    regexp alternate: #FF8000  255:128:0
-"    regexp alternate 2: #B18A3D  177:138:61
-"  variable: #C6C5FE  198:197:254
-"  
-" Misc colors:
-"  red color (used for whatever): #FF6C60   255:108:96 
-"     light red: #FFB6B0   255:182:176
-"
-"  brown: #E18964  good for special
-"
-"  lightpurpleish: #FFCCFF
-" 
-" Interface colors:
-"  background color: black
-"  cursor (where underscore is used): #FFA560  255:165:96
-"  cursor (where block is used): white
-"  visual selection: #1D1E2C  
-"  current line: #151515  21:21:21
-"  search selection: #07281C  7:40:28
-"  line number: #3D3D3D  61:61:61
-
-
-" ********************************************************************************
-" The following are the preferred 16 colors for your terminal
-"           Colors      Bright Colors
-" Black     #4E4E4E     #7C7C7C
-" Red       #FF6C60     #FFB6B0
-" Green     #A8FF60     #CEFFAB
-" Yellow    #FFFFB6     #FFFFCB
-" Blue      #96CBFE     #FFFFCB
-" Magenta   #FF73FD     #FF9CFE
-" Cyan      #C6C5FE     #DFDFFE
-" White     #EEEEEE     #FFFFFF
-
-
-" ********************************************************************************
+"Set up coloring
 hi clear
-
 if exists("syntax_on")
   syntax reset
 endif
 syntax on
+let colors_name = "issm_black"
 
-let colors_name = "issm_white"
+"preferred colors:
+"  0  : black
+"  9  : red
+" 15  : white
+" 20  : blue
+" 33  : cyan
+" 129 : dark purple
+" 202 : orange
+" 204 : light orange
+" 227 : yellow
+" 234 : very dark gray
+" 241 : dark gray
+" 244 : gray
+" 255 : light gray
 
-"                   GUI not used in terminal mode                     forground           background          style (reverse,bold,..)
-"hi Example         guifg=NONE        guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE
-
+"                forground    background   style (reverse,bold,..)
 " General colors
-hi Normal           guifg=#f6f3e8     guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-hi NonText          guifg=#070707     guibg=black       gui=NONE      ctermfg=129        ctermbg=NONE        cterm=NONE         "214 =orange
-
-hi Cursor           guifg=black       guibg=white       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=reverse      "cursor (mouse)
-hi LineNr           guifg=#3D3D3D     guibg=black       gui=NONE      ctermfg=249        ctermbg=232         cterm=NONE         "line numbering gray/blak 
-
-hi VertSplit        guifg=#202020     guibg=#202020     gui=NONE      ctermfg=241        ctermbg=241         cterm=NONE         "vertical split
-hi StatusLine       guifg=#CCCCCC     guibg=#202020     gui=italic    ctermfg=241        ctermbg=87          cterm=NONE         "87 = cyan
-hi StatusLineNC     guifg=black       guibg=#202020     gui=NONE      ctermfg=87         ctermbg=241         cterm=NONE         "241 = dark gray
-
-hi Folded           guifg=#a0a8b0     guibg=#384048     gui=NONE      ctermfg=NONE       ctermbg=129         cterm=NONE         "folded 129 = violet
-hi Title            guifg=#f6f3e8     guibg=NONE        gui=bold      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-hi Visual           guifg=NONE        guibg=#262D51     gui=NONE                         ctermbg=255         cterm=bold,reverse "visual 255 = white
-
-hi SpecialKey       guifg=#808080     guibg=#343434     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-
-hi WildMenu         guifg=green       guibg=yellow      gui=NONE      ctermfg=black      ctermbg=yellow      cterm=NONE          "?????
-hi PmenuSbar        guifg=black       guibg=white       gui=NONE      ctermfg=black      ctermbg=magenta     cterm=NONE          "????
-"hi Ignore           guifg=gray        guibg=black       gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=NONE
-
-hi Error            guifg=NONE        guibg=black       gui=NONE ctermfg=255      ctermbg=129         cterm=NONE
-hi ErrorMsg         guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=129         cterm=NONE                   " 196 = red
-hi WarningMsg       guifg=white       guibg=#FF6C60     gui=BOLD      ctermfg=255      ctermbg=201         cterm=NONE                   "201 = magenta
+hi Normal        ctermfg=NONE ctermbg=NONE cterm=NONE
+hi NonText       ctermfg=129  ctermbg=NONE cterm=NONE
+hi Cursor        ctermfg=NONE ctermbg=NONE cterm=reverse
+hi LineNr        ctermfg=15   ctermbg=241  cterm=NONE
+hi VertSplit     ctermfg=241  ctermbg=241  cterm=NONE
+hi StatusLine    ctermfg=241  ctermbg=33   cterm=NONE
+hi StatusLineNC  ctermfg=33   ctermbg=241  cterm=NONE
+hi Folded        ctermfg=93   ctermbg=254  cterm=NONE
+hi Title         ctermfg=NONE ctermbg=NONE cterm=NONE
+hi Visual        ctermfg=NONE ctermbg=NONE cterm=reverse
+hi SpecialKey    ctermfg=NONE ctermbg=NONE cterm=NONE
+hi WildMenu      ctermfg=0    ctermbg=227  cterm=NONE
+hi PmenuSbar     ctermfg=0    ctermbg=129  cterm=NONE
+hi Error         ctermfg=15   ctermbg=129  cterm=NONE
+hi ErrorMsg      ctermfg=15   ctermbg=129  cterm=NONE
+hi WarningMsg    ctermfg=15   ctermbg=129  cterm=NONE
 
 " Message displayed in lower left, such as --INSERT--
-hi ModeMsg          guifg=black       guibg=#C6C5FE     gui=BOLD      ctermfg=241      ctermbg=87        cterm=BOLD
-
+hi ModeMsg       ctermfg=0  ctermbg=33   cterm=BOLD
 if version >= 700 " Vim 7.x specific colors
-  hi CursorLine     guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
-  hi CursorColumn   guifg=NONE        guibg=#121212     gui=NONE      ctermfg=NONE       ctermbg=NONE        cterm=BOLD
-  hi MatchParen     guifg=#f6f3e8     guibg=#857b6f     gui=BOLD      ctermfg=87         ctermbg=241         cterm=BOLD,reverse  "matching parenthesis
-  hi Pmenu          guifg=#f6f3e8     guibg=#444444     gui=NONE      ctermfg=232        ctermbg=254         cterm=NONE "auto completion panel
-  hi PmenuSel       guifg=#000000     guibg=#cae682     gui=NONE      ctermfg=255        ctermbg=201        cterm=NONE
-  hi Search         guifg=NONE        guibg=NONE        gui=underline ctermfg=NONE       ctermbg=227         cterm=NONE  "227 = yellow
+  hi CursorLine   ctermfg=NONE ctermbg=NONE cterm=BOLD
+  hi CursorColumn ctermfg=NONE ctermbg=NONE cterm=BOLD
+  hi MatchParen   ctermfg=33   ctermbg=241  cterm=reverse "matching parenthesis
+  hi Pmenu        ctermfg=0    ctermbg=15   cterm=NONE    "auto completion panel
+  hi PmenuSel     ctermfg=255  ctermbg=241  cterm=NONE
+  hi Search       ctermfg=0    ctermbg=220  cterm=NONE
 endif
 
 " Syntax highlighting
-hi Comment          guifg=#7C7C7C     guibg=NONE        gui=NONE      ctermfg=243         ctermbg=NONE        cterm=NONE
-hi String           guifg=#A8FF60     guibg=NONE        gui=NONE      ctermfg=40          ctermbg=NONE        cterm=NONE
-hi Number           guifg=#FF73FD     guibg=NONE        gui=NONE      ctermfg=201         ctermbg=NONE        cterm=NONE
+hi Comment      ctermfg=241  ctermbg=NONE cterm=NONE
+hi String       ctermfg=28   ctermbg=NONE cterm=NONE
+hi Number       ctermfg=201  ctermbg=NONE cterm=NONE
+hi Keyword      ctermfg=9    ctermbg=NONE cterm=NONE  " matlab function
+hi PreProc      ctermfg=9    ctermbg=NONE cterm=NONE  " def undef include
+hi Conditional  ctermfg=220  ctermbg=NONE cterm=NONE  " if else end
+hi Todo         ctermfg=204  ctermbg=NONE cterm=NONE
+hi Constant     ctermfg=196  ctermbg=NONE cterm=NONE
+hi Identifier   ctermfg=9    ctermbg=NONE cterm=NONE
+hi Function     ctermfg=20   ctermbg=NONE cterm=NONE "functions 20 = pastel blue
+hi Type         ctermfg=33   ctermbg=NONE cterm=NONE "cterm matlab global
+hi Statement    ctermfg=20   ctermbg=NONE cterm=NONE "cd ls sed mv
+hi Special      ctermfg=202  ctermbg=NONE cterm=NONE " matlab '...'
+hi Delimiter    ctermfg=NONE ctermbg=NONE cterm=NONE " [ ]
+hi Operator     ctermfg=202  ctermbg=NONE cterm=NONE " == &
+hi Directory    ctermfg=33   ctermbg=NONE cterm=NONE " == & 
 
-hi Keyword          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=196          ctermbg=NONE        cterm=NONE  " matlab function
-hi PreProc          guifg=#96CBFE     guibg=NONE        gui=NONE      ctermfg=196         ctermbg=NONE        cterm=NONE   " def undef include
-hi Conditional      guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=93         ctermbg=NONE        cterm=NONE  " if else end
-
-hi Todo             guifg=#8f8f8f     guibg=NONE        gui=NONE      ctermfg=18         ctermbg=NONE        cterm=NONE
-hi Constant         guifg=#99CC99     guibg=NONE        gui=NONE      ctermfg=21         ctermbg=NONE        cterm=NONE
-
-hi Identifier       guifg=#C6C5FE     guibg=NONE        gui=NONE      ctermfg=21          ctermbg=NONE        cterm=NONE
-hi Function         guifg=#FFD2A7     guibg=NONE        gui=NONE      ctermfg=69          ctermbg=NONE        cterm=NONE "functions 69 = pastel blue
-hi Type             guifg=#FFFFB6     guibg=NONE        gui=NONE      ctermfg=165         ctermbg=NONE        cterm=NONE
-hi Statement        guifg=#6699CC     guibg=NONE        gui=NONE      ctermfg=69         ctermbg=NONE        cterm=NONE " cd ls sed mv
-
-hi Special          guifg=#E18964     guibg=NONE        gui=NONE      ctermfg=43          ctermbg=NONE        cterm=NONE  " ; 202  = orange 
-hi Delimiter        guifg=#00A0A0     guibg=NONE        gui=NONE      ctermfg=NONE        ctermbg=NONE        cterm=NONE  " [ ]
-hi Operator         guifg=white       guibg=NONE        gui=NONE      ctermfg=43          ctermbg=NONE        cterm=NONE  " == &  178 = darkyellow
-
-hi link Character       Constant
-hi link Boolean         Constant
-hi link Float           Number
-hi link Repeat          Statement
-hi link Label           Statement
-hi link Exception       Statement
-hi link Include         PreProc
-hi link Define          PreProc
-hi link Macro           PreProc
-hi link PreCondit       PreProc
-hi link StorageClass    Type
-hi link Structure       Type
-hi link Typedef         Type
-hi link Tag             Special
-hi link SpecialChar     Special
-hi link SpecialComment  Special
-hi link Debug           Special
-
-
-" Special for Ruby
-hi rubyRegexp                  guifg=#B18A3D      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
-hi rubyRegexpDelimiter         guifg=#FF8000      guibg=NONE      gui=NONE      ctermfg=brown          ctermbg=NONE      cterm=NONE
-hi rubyEscape                  guifg=white        guibg=NONE      gui=NONE      ctermfg=cyan           ctermbg=NONE      cterm=NONE
-hi rubyInterpolationDelimiter  guifg=#00A0A0      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE
-hi rubyControl                 guifg=#6699CC      guibg=NONE      gui=NONE      ctermfg=blue           ctermbg=NONE      cterm=NONE  "and break, etc
-"hi rubyGlobalVariable          guifg=#FFCCFF      guibg=NONE      gui=NONE      ctermfg=lightblue      ctermbg=NONE      cterm=NONE  "yield
-hi rubyStringDelimiter         guifg=#336633      guibg=NONE      gui=NONE      ctermfg=lightgreen     ctermbg=NONE      cterm=NONE
-"rubyInclude
-"rubySharpBang
-"rubyAccess
-"rubyPredefinedVariable
-"rubyBoolean
-"rubyClassVariable
-"rubyBeginEnd
-"rubyRepeatModifier
-"hi link rubyArrayDelimiter    Special  " [ , , ]
-"rubyCurlyBlock  { , , }
-
-hi link rubyClass             Keyword 
-hi link rubyModule            Keyword 
-hi link rubyKeyword           Keyword 
-hi link rubyOperator          Operator
-hi link rubyIdentifier        Identifier
-hi link rubyInstanceVariable  Identifier
-hi link rubyGlobalVariable    Identifier
-hi link rubyClassVariable     Identifier
-hi link rubyConstant          Type  
-
-
-" Special for Java
-" hi link javaClassDecl    Type
-hi link javaScopeDecl         Identifier 
-hi link javaCommentTitle      javaDocSeeTag 
-hi link javaDocTags           javaDocSeeTag 
-hi link javaDocParam          javaDocSeeTag 
-hi link javaDocSeeTagParam    javaDocSeeTag 
-
-hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
-hi javaDocSeeTag              guifg=#CCCCCC     guibg=NONE        gui=NONE      ctermfg=darkgray    ctermbg=NONE        cterm=NONE
-"hi javaClassDecl              guifg=#CCFFCC     guibg=NONE        gui=NONE      ctermfg=white       ctermbg=NONE        cterm=NONE
-
-
-" Special for XML
-hi link xmlTag          Keyword 
-hi link xmlTagName      Conditional 
-hi link xmlEndTag       Identifier 
-
-
-" Special for HTML
-hi link htmlTag         Keyword 
-hi link htmlTagName     Conditional 
-hi link htmlEndTag      Identifier 
-
-
-" Special for Javascript
-hi link javaScriptNumber      Number 
-
-
-" Special for Python
-"hi  link pythonEscape         Keyword      
-
-
-" Special for CSharp
-hi  link csXmlTag             Keyword      
-
-
-" Special for PHP
+"Specific for diff
+hi DiffAdd      cterm=none ctermfg=0 ctermbg=119
+hi DiffChange   cterm=none ctermfg=0 ctermbg=228
+hi DiffText     cterm=none ctermfg=0 ctermbg=178
+hi DiffDelete   cterm=none ctermfg=0 ctermbg=197
+hi diffLine     cterm=bold ctermfg=241
+hi diffOldLine  cterm=none ctermfg=241
+hi diffOldFile  cterm=none ctermfg=241
+hi diffNewFile  cterm=none ctermfg=241
+hi diffAdded    cterm=none
+hi diffRemoved  cterm=none ctermfg=9
+hi diffChanged  cterm=none ctermfg=20
Index: /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13974)
+++ /issm/trunk/externalpackages/vim/addons/vim/syntax/c.vim	(revision 13975)
@@ -569,7 +569,24 @@
 "ISSM's objects end
 "ISSM's Enums begin
-syn keyword cConstant AutodiffForwardEnum
 syn keyword cConstant AutodiffIsautodiffEnum
-syn keyword cConstant AutodiffReverseEnum
+syn keyword cConstant AutodiffNumDependentsEnum
+syn keyword cConstant AutodiffNumDependentObjectsEnum
+syn keyword cConstant AutodiffDependentObjectNamesEnum
+syn keyword cConstant AutodiffDependentObjectTypesEnum
+syn keyword cConstant AutodiffDependentObjectIndicesEnum
+syn keyword cConstant AutodiffDependentObjectsEnum
+syn keyword cConstant AutodiffNumIndependentsEnum
+syn keyword cConstant AutodiffNumIndependentObjectsEnum
+syn keyword cConstant AutodiffIndependentObjectNamesEnum
+syn keyword cConstant AutodiffIndependentObjectTypesEnum
+syn keyword cConstant AutodiffIndependentObjectsEnum
+syn keyword cConstant AutodiffJacobianEnum
+syn keyword cConstant AutodiffXpEnum
+syn keyword cConstant AutodiffDriverEnum
+syn keyword cConstant AutodiffFosForwardIndexEnum
+syn keyword cConstant AutodiffFovForwardIndicesEnum
+syn keyword cConstant AutodiffFosReverseIndexEnum
+syn keyword cConstant AutodiffMassFluxSegmentsPresentEnum
+syn keyword cConstant AutodiffKeepEnum
 syn keyword cConstant BalancethicknessSpcthicknessEnum
 syn keyword cConstant BalancethicknessStabilizationEnum
@@ -583,4 +600,5 @@
 syn keyword cConstant ConstantsReferencetemperatureEnum
 syn keyword cConstant ConstantsYtsEnum
+syn keyword cConstant DependentObjectEnum
 syn keyword cConstant DiagnosticAbstolEnum
 syn keyword cConstant DiagnosticIcefrontEnum
@@ -607,4 +625,5 @@
 syn keyword cConstant FlowequationElementEquationEnum
 syn keyword cConstant FlowequationIshutterEnum
+syn keyword cConstant FlowequationIsl1l2Enum
 syn keyword cConstant FlowequationIsmacayealpattynEnum
 syn keyword cConstant FlowequationIsstokesEnum
@@ -621,4 +640,5 @@
 syn keyword cConstant HydrologySpcwatercolumnEnum
 syn keyword cConstant HydrologyStabilizationEnum
+syn keyword cConstant IndependentObjectEnum
 syn keyword cConstant InversionControlParametersEnum
 syn keyword cConstant InversionCostFunctionEnum
@@ -658,4 +678,6 @@
 syn keyword cConstant MaterialsRheologyLawEnum
 syn keyword cConstant MaterialsRheologyNEnum
+syn keyword cConstant MaterialsRheologyZEnum
+syn keyword cConstant MaterialsRheologyZbarEnum
 syn keyword cConstant MaterialsRhoIceEnum
 syn keyword cConstant MaterialsRhoWaterEnum
@@ -692,6 +714,10 @@
 syn keyword cConstant PrognosticStabilizationEnum
 syn keyword cConstant PrognosticVertexPairingEnum
+syn keyword cConstant PrognosticNumRequestedOutputsEnum
+syn keyword cConstant PrognosticRequestedOutputsEnum
 syn keyword cConstant QmuIsdakotaEnum
-syn keyword cConstant QmuMassFluxSegmentsEnum
+syn keyword cConstant MassFluxSegmentsEnum
+syn keyword cConstant MassFluxSegmentsPresentEnum
+syn keyword cConstant QmuMassFluxSegmentsPresentEnum
 syn keyword cConstant QmuNumberofpartitionsEnum
 syn keyword cConstant QmuNumberofresponsesEnum
@@ -728,4 +754,6 @@
 syn keyword cConstant SurfaceforcingsMonthlytemperaturesEnum
 syn keyword cConstant SurfaceforcingsHcEnum
+syn keyword cConstant SurfaceforcingsHrefEnum
+syn keyword cConstant SurfaceforcingsSmbrefEnum
 syn keyword cConstant SurfaceforcingsSmbPosMaxEnum
 syn keyword cConstant SurfaceforcingsSmbPosMinEnum
@@ -789,9 +817,10 @@
 syn keyword cConstant TransientSolutionEnum
 syn keyword cConstant ApproximationEnum
+syn keyword cConstant NoneApproximationEnum
 syn keyword cConstant HutterApproximationEnum
 syn keyword cConstant MacAyealApproximationEnum
 syn keyword cConstant MacAyealPattynApproximationEnum
 syn keyword cConstant MacAyealStokesApproximationEnum
-syn keyword cConstant NoneApproximationEnum
+syn keyword cConstant L1L2ApproximationEnum
 syn keyword cConstant PattynApproximationEnum
 syn keyword cConstant PattynStokesApproximationEnum
@@ -804,4 +833,6 @@
 syn keyword cConstant VerticesEnum
 syn keyword cConstant ResultsEnum
+syn keyword cConstant GenericParamEnum
+syn keyword cConstant AdolcParamEnum
 syn keyword cConstant BoolInputEnum
 syn keyword cConstant BoolParamEnum
@@ -811,4 +842,5 @@
 syn keyword cConstant DofIndexingEnum
 syn keyword cConstant DoubleInputEnum
+syn keyword cConstant DataSetParamEnum
 syn keyword cConstant DoubleMatArrayParamEnum
 syn keyword cConstant DoubleMatParamEnum
@@ -829,8 +861,10 @@
 syn keyword cConstant MacAyeal3dIceFrontEnum
 syn keyword cConstant MaticeEnum
+syn keyword cConstant MatdamageiceEnum
 syn keyword cConstant MatparEnum
 syn keyword cConstant NodeEnum
 syn keyword cConstant NumericalfluxEnum
 syn keyword cConstant ParamEnum
+syn keyword cConstant L1L2IceFrontEnum
 syn keyword cConstant PattynIceFrontEnum
 syn keyword cConstant PengridEnum
@@ -838,4 +872,5 @@
 syn keyword cConstant PentaEnum
 syn keyword cConstant PentaP1InputEnum
+syn keyword cConstant ProfilerEnum
 syn keyword cConstant MatrixParamEnum
 syn keyword cConstant VectorParamEnum
@@ -903,4 +938,6 @@
 syn keyword cConstant TemperatureOldEnum
 syn keyword cConstant TemperaturePicardEnum
+syn keyword cConstant TemperatureSurfaceEnum
+syn keyword cConstant TemperatureBasalEnum
 syn keyword cConstant ThicknessAbsMisfitEnum
 syn keyword cConstant TypeEnum
@@ -924,4 +961,6 @@
 syn keyword cConstant EnthalpyPicardEnum
 syn keyword cConstant ThicknessAbsGradientEnum
+syn keyword cConstant ThicknessAlongGradientEnum
+syn keyword cConstant ThicknessAcrossGradientEnum
 syn keyword cConstant StepResponsesEnum
 syn keyword cConstant IntMatParamEnum
@@ -944,8 +983,4 @@
 syn keyword cConstant StressTensoryzEnum
 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
@@ -981,4 +1016,6 @@
 syn keyword cConstant MaxVzEnum
 syn keyword cConstant MaxAbsVzEnum
+syn keyword cConstant IceVolumeEnum
+syn keyword cConstant TotalSmbEnum
 syn keyword cConstant RelativeEnum
 syn keyword cConstant AbsoluteEnum
@@ -1004,4 +1041,6 @@
 syn keyword cConstant OldGradientEnum
 syn keyword cConstant OutputFilePointerEnum
+syn keyword cConstant OutputFileNameEnum
+syn keyword cConstant LockFileNameEnum
 syn keyword cConstant PetscOptionsAnalysesEnum
 syn keyword cConstant PetscOptionsStringsEnum
@@ -1020,4 +1059,5 @@
 syn keyword cConstant XYZPEnum
 syn keyword cConstant OptionEnum
+syn keyword cConstant GenericOptionEnum
 syn keyword cConstant OptionCellEnum
 syn keyword cConstant OptionCharEnum
Index: /issm/trunk/externalpackages/vim/addons/vimrc
===================================================================
--- /issm/trunk/externalpackages/vim/addons/vimrc	(revision 13974)
+++ /issm/trunk/externalpackages/vim/addons/vimrc	(revision 13975)
@@ -1,4 +1,4 @@
 
-" General setup{{{1
+" General setup{{{
 " ----------------------------------------------------------------------
 " Use Vim settings, rather then Vi settings (much better!).
@@ -18,5 +18,5 @@
 set showmode
 "----------------------------------------------------------------------}}}
-" Text-Formatting, Identing, Tabbing{{{1
+" Text-Formatting, Identing, Tabbing{{{
 " ----------------------------------------------------------------------
 " allow backspacing (to delete) over everything in insert mode
@@ -39,5 +39,5 @@
 set foldtext=IssmFoldText()
 " -----------------------------------------------------------}}}
-" Backups {{{1
+" Backups {{{
 " -----------------------------------------------------------
 " updatecount   number of characters typed to cause a swap file update (0->disable)
@@ -46,5 +46,5 @@
 set nobackup
 " -----------------------------------------------------------}}}
-" Searching, Substituting {{{1
+" Searching, Substituting {{{
 " -----------------------------------------------------------
 " select case-insenitive search
@@ -75,5 +75,5 @@
 set su=.h,.bak,~,.o,.info,.swp,.obj
 " ----------------------------------------------------------------------}}}
-" Colors and theme {{{1
+" Colors and theme {{{
 " ----------------------------------------------------------------------
 " use 256 colors
@@ -88,5 +88,5 @@
 " ----------------------------------------------------------------------}}}
 
-" Mappings{{{1
+" Mappings{{{
 " ----------------------------------------------------------------------
 "stop highlightings when spce is pressed
@@ -111,5 +111,5 @@
 map Q gq
 " ----------------------------------------------------------------------}}}
-" Autocommands {{{1
+" Autocommands {{{
 " ----------------------------------------------------------------------
 " Only do this part when compiled with support for autocommands.
@@ -140,5 +140,5 @@
 endif " has("autocmd")
 " ----------------------------------------------------------------------}}}
-" Matlab special {{{1
+" Matlab special {{{
 " ----------------------------------------------------------------------
 "" associate *.par with matlab filetype
@@ -146,5 +146,5 @@
 au BufRead,BufNewFile *.tpl setfiletype html
 " ----------------------------------------------------------------------}}}
-" C special{{{1
+" C special{{{
 " ----------------------------------------------------------------------
 "indenting for C-code
@@ -153,5 +153,5 @@
 set cinoptions={.5s,+.5s,t0,n-2,p2s,(03s,=.5s,>1s,=1s,:1s 
 " ----------------------------------------------------------------------}}}
-" TEX special{{{1
+" TEX special{{{
 " ----------------------------------------------------------------------
 au BufRead,BufNewFile *.tex,*.html set textwidth=100     "100 caracters max (See gq command)
@@ -165,9 +165,9 @@
 let g:tex_flavor='latex'
 " ----------------------------------------------------------------------}}}
-" FORTRAN special{{{1
+" FORTRAN special{{{
 " ----------------------------------------------------------------------
 au BufRead,BufNewFile *.src setfiletype fortran
 " ----------------------------------------------------------------------}}}
-" InsertTabWrapper{{{1
+" InsertTabWrapper{{{
 " ----------------------------------------------------------------------
 function! InsertTabWrapper(direction) 
@@ -192,5 +192,5 @@
 " ----------------------------------------------------------------------}}}
 
-" Abbreviations {{{1
+" Abbreviations {{{
 " ----------------------------------------------------------------------
 "func Eatchar(pat)
@@ -225,5 +225,5 @@
 "au BufRead,BufNewFile *.tex ab (()) \left( \right)
 "}}}
-" Skeletons {{{1
+" Skeletons {{{
 au BufNewFile letter.tex   0r ~/.vim/xtr/skeleton/letter.tex
 "}}}
Index: /issm/trunk/m4/issm_options.m4
===================================================================
--- /issm/trunk/m4/issm_options.m4	(revision 13974)
+++ /issm/trunk/m4/issm_options.m4	(revision 13975)
@@ -14,5 +14,5 @@
 
 	dnl }}}
-    dnl shared build {{{
+    dnl Shared build {{{
     AC_ARG_ENABLE([sharedlibs],                                                dnl feature
         AS_HELP_STRING([--enable-sharedlibs], [produce libISSM.so.0]),         dnl help string
@@ -21,6 +21,5 @@
     AM_CONDITIONAL([SHAREDLIBS], [test x$enable_sharedlibs = xyes])
     dnl }}}
-
-    dnl shared build {{{
+    dnl Version{{{
     AC_ARG_ENABLE([version],                                                dnl feature
         AS_HELP_STRING([--enable-version], [produce libISSM.so.0]),         dnl help string
@@ -29,12 +28,11 @@
     AM_CONDITIONAL([VERSION], [test x$enable_VERSION = xyes])
     dnl }}}
-
-	dnl Modules build {{{
-	AC_ARG_WITH([modules],
-		AS_HELP_STRING([--with-modules = value],[modules compilation. ]),
-		[MODULES_VALUE=$withval],[MODULES_VALUE="yes"])
-	AC_MSG_CHECKING(for modules compilation)
-	AM_CONDITIONAL([MODULES], [test $MODULES_VALUE = yes])
-	AC_MSG_RESULT($MODULES_VALUE) 
+	dnl Wrappers build {{{
+	AC_ARG_WITH([wrappers],
+		AS_HELP_STRING([--with-wrappers = value],[wrappers compilation. ]),
+		[WRAPPERS_VALUE=$withval],[WRAPPERS_VALUE="yes"])
+	AC_MSG_CHECKING(for wrappers compilation)
+	AM_CONDITIONAL([WRAPPERS], [test x$WRAPPERS_VALUE = xyes])
+	AC_MSG_RESULT($WRAPPERS_VALUE) 
 	dnl }}}
 	dnl Extensions{{{
@@ -80,6 +78,6 @@
 			export CC=icc
 			export CXX=icpc
-			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ "
-			export CFLAGS=" -O3 -D_INTEL_LINUX_ "
+			export CXXFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
+			export CFLAGS=" -O3 -D_INTEL_LINUX_ -DMPICH_IGNORE_CXX_SEEK"
 		elif test $VENDOR = intel-pleiades; then
 			export CC=icc
@@ -94,5 +92,5 @@
 	AC_MSG_RESULT(done)
 	dnl }}}
-	dnl Matlab{{{
+	dnl matlab{{{
 
 	dnl 1. See if matlab has been provided
@@ -113,69 +111,7 @@
 	AM_CONDITIONAL([MATLAB], [test x$HAVE_MATLAB = xyes])
 
-	dnl 2. if matlab is provided, get version number
+	dnl 2. Get Matlab libraries
 	if test x$HAVE_MATLAB = xyes; then
-		AC_MSG_CHECKING([for matlab version])
-		MATLAB_VERSION=""
-
-		dnl For Matlab R2008a and more, the version number is stored in .VERSION
-		if test -f "$MATLAB_ROOT/.VERSION" ; then
-			MATLAB_VERSION=$(cat $MATLAB_ROOT/.VERSION)
-		fi
-		dnl Otherwise find version in file stored in bin/util/mex/version.txt
-		if test -f "$MATLAB_ROOT/bin/util/mex/version.txt" ; then
-			MATLAB_VERSION=$(cat $MATLAB_ROOT/bin/util/mex/version.txt)
-		fi
-
-		dnl check that we found the version
-		if test -z "$MATLAB_VERSION" ; then
-			AC_MSG_ERROR([Matlab version not found])
-		fi
-
-		case $MATLAB_VERSION in
-			@<:@1-9@:>@.@<:@0-9@:>@ | @<:@1-9@:>@@<:@0-9@:>@.@<:@0-9@:>@ | @<:@1-9@:>@.@<:@1-9@:>@@<:@0-9@:>@)
-				MATLAB_MAJOR=$(echo $MATLAB_VERSION | sed -e "s/^\(@<:@0-9@:>@*\)\.@<:@0-9@:>@*.*/\1/")
-				MATLAB_MINOR=$(echo $MATLAB_VERSION | sed -e "s/^@<:@0-9@:>@*\.\(@<:@0-9@:>@*\).*/\1/")
-				;;
-			R2007a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=4
-			  ;;
-			R2008a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=6
-			  ;;
-			R2009a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=8
-			  ;;
-			R2010a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=10
-			  ;;
-			R2010b)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=11
-			  ;;
-			R2011a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=12
-			  ;;
-			R2011b)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=13
-			  ;;
-			R2012a)
-			  MATLAB_MAJOR=7
-			  MATLAB_MINOR=14
-			  ;;
-			*)
-			  AC_MSG_ERROR([can not determine Matlab version number])
-			esac
-		AC_SUBST([MATLAB_VERSION])
-		AC_SUBST([MATLAB_MAJOR])
-		AC_SUBST([MATLAB_MINOR])
-		AC_MSG_RESULT($MATLAB_VERSION ($MATLAB_MAJOR.$MATLAB_MINOR))
-
-		dnl 3. Get Matlab libraries
+
 		AC_MSG_CHECKING(for matlab headers and libraries in $MATLAB_ROOT)
 		MATLABINCL=-I"$MATLAB_ROOT/extern/include";
@@ -185,42 +121,4 @@
 		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)
 
@@ -332,28 +230,35 @@
 	  AS_HELP_STRING([--with-python-dir=DIR], [python root directory.]),
 	  [PYTHON_ROOT=$withval],[PYTHON_ROOT=""]) 
+
 	AC_MSG_CHECKING(for python)
-	
 	if test -d "$PYTHON_ROOT"; then
-		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=""])
+		HAVE_PYTHON="yes"
+		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
+	else
+		HAVE_PYTHON=no
+	fi
+	AC_MSG_RESULT($HAVE_PYTHON)
+
+	dnl get python version
+	if test x$HAVE_PYTHON = xyes; then
 		AC_MSG_CHECKING(for python version)
+		dnl Query Python for its version number.  Getting [:3] seems to be
+		dnl the best way to do this; it's what "site.py" does in the standard
+		dnl library.
+		PYTHON_VERSION=$($PYTHON_ROOT/bin/python -c "import sys; print sys.version[[:3]]")
+		AC_MSG_RESULT($PYTHON_VERSION)
 
 		dnl recover major: 
-		PYTHON_MAJOR=${PYTHONVERSION%.*}
-
+		PYTHON_MAJOR=${PYTHON_VERSION%.*}
 		if test x$PYTHON_MAJOR = x3; then
 			dnl are we running python 3?
 			HAVE_PYTHON3="yes"
+		else
+			HAVE_PYTHON3="no"
 		fi
 		AC_DEFINE_UNQUOTED([_PYTHON_MAJOR_],$PYTHON_MAJOR,[python version major])
-		AC_MSG_RESULT($PYTHON_MAJOR)
 
 		PYTHONINCL=-I$PYTHON_ROOT/include
-		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHONVERSION"
+		PYTHONLIB="-L$PYTHON_ROOT/lib -lpython$PYTHON_VERSION"
 		PYTHONEXT=.so
 
@@ -370,5 +275,4 @@
 		esac
 
-		AC_DEFINE([_HAVE_PYTHON_],[1],[with Python in ISSM src])
 		AC_SUBST([PYTHONINCL])
 		AC_SUBST([PYTHONLIB])
@@ -376,11 +280,7 @@
 		AC_SUBST([PYTHONWRAPPEREXT])
 		AC_SUBST([PYTHONLINK])
-	else
-		HAVE_PYTHON=no
 	fi
 	AM_CONDITIONAL([PYTHON], [test x$HAVE_PYTHON = xyes])
 	AM_CONDITIONAL([PYTHON3], [test x$HAVE_PYTHON3 = xyes])
-	AC_MSG_RESULT($HAVE_PYTHON)
-
 	dnl }}}
 	dnl python-numpy{{{
@@ -556,67 +456,4 @@
 	AM_CONDITIONAL([ROSE], [test x$HAVE_ROSE = xyes])
 	AC_MSG_RESULT($HAVE_ROSE)
-	dnl }}}
-	dnl metis{{{
-	AC_ARG_WITH([metis-dir],
-	  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
-	  [METIS_ROOT=$withval],[METIS_ROOT=""])
-
-   AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
-
-	if test -d "$METIS_ROOT"; then
-
-		dnl first figure out version of metis: does the VERSION file exist?
-		if test -e "$METIS_ROOT/VERSION"; then
-			METIS_VERSION=4
-		else
-			METIS_VERSION=5
-		fi
-
-		dnl defaults
-		HAVE_METIS=yes
-
-		if test "$METIS_VERSION" = "4" ; then
-   			
-			METISINCL=-I"$METIS_ROOT/Lib" 
-			case "${host_os}" in
-				*cygwin*)
-				METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
-				;;
-				*linux*)
-				METISLIB=-L"$METIS_ROOT/ -lmetis"
-				;;
-				*darwin*)
-				METISLIB=-L"$METIS_ROOT/ -lmetis"
-				;;
-			esac
-
-   			AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
-		fi
-		if test "$METIS_VERSION" = "5" ; then
-	
-			case "${host_os}" in
-				*cygwin*)
-				METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
-				;;
-				*linux*)
-				METISLIB=-L"$METIS_ROOT/lib -lmetis"
-				;;
-				*darwin*)
-				METISLIB=-L"$METIS_ROOT/lib -lmetis"
-				;;
-			esac
-
-			METISINCL=-I"$METIS_ROOT/include" 
-			AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
-		fi
-
-		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
-		AC_SUBST([METISINCL])
-		AC_SUBST([METISLIB])
-	else
-		HAVE_METIS=no
-	fi
-	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
-	AC_MSG_RESULT($HAVE_METIS)
 	dnl }}}
 	dnl mpi{{{
@@ -681,34 +518,42 @@
 	if test -d "$PETSC_ROOT"; then
 
-		PETSCINCL="-I$PETSC_ROOT/$PETSC_ARCH/include -I$PETSC_ROOT/include/$PETSC_ARCH/ -I$PETSC_ROOT/include -I$PETSC_ROOT/ -I$PETSC_ROOT/bmake/$PETSC_ARCH -I$PETSC_ROOT/src/mat/impls/dense/mpi/plapack/"
-	
-		case "${host_os}" in
+	 PETSCINCL=" -I$PETSC_ROOT/include"
+	 dnl Add other location (maybe not needed anymore)
+	 if test -d "$PETSC_ROOT/$PETSC_ARCH/include"; then
+	  PETSCINCL+=" $PETSC_ROOT/$PETSC_ARCH/include"
+	 fi
+	 if test -d "$PETSC_ROOT/include/$PETSC_ARCH"; then
+	  PETSCINCL+=" $PETSC_ROOT/include/$PETSC_ARCH"
+	 fi
+	
+	 case "${host_os}" in
 			*cygwin*)
-			if test "$PETSC_MAJOR" = "2" ; then
-				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"
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" libpetscksp.lib libpetscdm.lib libpetscmat.lib libpetscvec.lib libpetscsnes.lib libpetscts.lib libmpiuni.lib libpetsc.lib"
 			else
-				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib\" -LIBPATH:\"$PETSC_ROOT/lib/$PETSC_ARCH\" libpetsc.lib"
+				PETSCLIB="-link -LIBPATH:\"$PETSC_ROOT/lib\" libpetsc.lib"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" libmetis.lib"; fi
 			fi
 			;;
 			*linux*)
-			if test "$PETSC_MAJOR" = "2" ; then
-			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetsc  -lpetscsnes -lpetscts"
 			else
-			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc -ldl"
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc -ldl"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
 			fi
 			;;
 			*darwin*)
-			if test "$PETSC_MAJOR" = "2" ; then
-			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"
+			if test $PETSC_MAJOR -lt 3 ; then
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsnes -lpetscts -lpetsc"
 			else
-			PETSCLIB="-L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH/ -L$PETSC_ROOT/lib -L$PETSC_ROOT/lib/$PETSC_ARCH -lpetsc"
+				PETSCLIB="-L$PETSC_ROOT/lib -lpetsc"
+				if test $PETSC_MAJOR -gt 3 || test $PETSC_MINOR -ge 3; then PETSCLIB+=" -lmetis"; fi
 			fi
 			;;
 		esac
-
 		AC_DEFINE([_HAVE_PETSC_],[1],[with PETSc in ISSM src])
 		AC_SUBST([PETSCINCL])
 		AC_SUBST([PETSCLIB])
-
 		HAVE_PETSC=yes
 	else
@@ -718,4 +563,75 @@
 	AM_CONDITIONAL([PETSC], [test x$HAVE_PETSC = xyes])
 	AC_MSG_RESULT($HAVE_PETSC)
+	dnl }}}
+	dnl metis{{{
+	if test "$HAVE_PETSC" = "yes" && test "x$PETSC_MAJOR" = "x3" && test $PETSC_MINOR -ge 3; then
+
+		dnl in petsc >=3.3, metis is provided
+		HAVE_METIS="yes"
+		AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+		AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+	else
+		AC_ARG_WITH([metis-dir],
+		  AS_HELP_STRING([--with-metis-dir=DIR],[metis root directory. necessary for serial build]),
+		  [METIS_ROOT=$withval],[METIS_ROOT=""])
+
+		AC_MSG_CHECKING(for metis headers and libraries in $METIS_ROOT)
+
+		if test -d "$METIS_ROOT"; then
+
+			dnl first figure out version of metis: does the VERSION file exist?
+			if test -e "$METIS_ROOT/VERSION"; then
+				METIS_VERSION=4
+			else
+				METIS_VERSION=5
+			fi
+
+			dnl defaults
+			HAVE_METIS=yes
+
+			if test "$METIS_VERSION" = "4" ; then
+					
+				METISINCL=-I"$METIS_ROOT/Lib" 
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/ -lmetis"
+					;;
+				esac
+
+					AC_DEFINE([_METIS_VERSION_],[4],[ Metis version number])
+			fi
+			if test "$METIS_VERSION" = "5" ; then
+		
+				case "${host_os}" in
+					*cygwin*)
+					METISLIB="-LIBPATH:\"$METIS_ROOT\" libmetis.lib"
+					;;
+					*linux*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+					*darwin*)
+					METISLIB=-L"$METIS_ROOT/lib -lmetis"
+					;;
+				esac
+
+				METISINCL=-I"$METIS_ROOT/include" 
+				AC_DEFINE([_METIS_VERSION_],[5],[ Metis version number])
+			fi
+
+			AC_DEFINE([_HAVE_METIS_],[1],[with Metis in ISSM src])
+			AC_SUBST([METISINCL])
+			AC_SUBST([METISLIB])
+		else
+			HAVE_METIS=no
+		fi
+		AC_MSG_RESULT($HAVE_METIS)
+	fi
+	AM_CONDITIONAL([METIS], [test x$HAVE_METIS = xyes])
 	dnl }}}
 	dnl tao{{{
@@ -1400,4 +1316,31 @@
 	AC_MSG_RESULT($HAVE_RIFTS)
 	dnl }}}
+	dnl with-android{{{
+	AC_ARG_WITH([android],
+		AS_HELP_STRING([--with-android = EXE], [compile with android capabilities (default is no, alternatives are exe and jni)]),
+		[ANDROID=$withval],[ANDROID=no]) 
+	AC_MSG_CHECKING(for android capability compilation)
+
+	if test "x$ANDROID" = "xjni"; then
+
+		dnl defaults
+		HAVE_ANDROID=jni
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xexe"; then
+		dnl defaults
+		HAVE_ANDROID=exe
+
+		AC_DEFINE([_HAVE_ANDROID_],[1],[with android capability])
+	elif test "x$ANDROID" = "xno"; then
+		HAVE_ANDROID=no
+	else
+	  AC_MSG_ERROR([--with-android should be either no, exe or jni])
+	fi
+	AM_CONDITIONAL([ANDROID], [test x$HAVE_ANDROID != xno])
+	AM_CONDITIONAL([ANDROIDJNI], [test x$HAVE_ANDROID = xjni])
+	AM_CONDITIONAL([ANDROIDEXE], [test x$HAVE_ANDROID = xexe])
+	AC_MSG_RESULT($HAVE_ANDROID)
+	dnl }}}
 	dnl with-3d{{{
 	AC_ARG_WITH([3d],
@@ -1433,17 +1376,8 @@
 	fi
 
-	dnl check that we have python version if python compile is specified
-	if test "$HAVE_PYTHON" = "yes"  && test "$PYTHONVERSION" = "" ; then
-	AC_MSG_ERROR([need python-version if python compile is required!]);
-	fi
-
 	dnl check that if we have MPI, we have metis
 	if test "$HAVE_METIS" = "yes"  && test "$HAVE_MPI" = "no" ; then
 	AC_MSG_ERROR([need mpi if using the metis partitioner!]);
 	fi
-
-
-
-
 
 	AC_MSG_RESULT(done)
@@ -1503,12 +1437,3 @@
 	AC_MSG_RESULT($USE_64BIT_INDICES)
 	dnl }}}
-	dnl circular-dependency{{{
-	AC_ARG_WITH([circular-dependency],
-	  AS_HELP_STRING([--with-circular-dependency = bool],[do we look for circular dependencies, default "yes", ex: --with-circular-dependency="no"]),
-	  [CIRCULAR_DEPENDENCIES=$withval],[CIRCULAR_DEPENDENCIES=yes]) 
-	AC_MSG_CHECKING(for circular dependencies)
-	AM_CONDITIONAL([CIRCULAR_DEPENDENCIES], [test x$CIRCULAR_DEPENDENCIES = xyes])
-	AC_MSG_RESULT($CIRCULAR_DEPENDENCIES) 
-
-	dnl }}}
 ])
Index: /issm/trunk/scripts/BinRead.py
===================================================================
--- /issm/trunk/scripts/BinRead.py	(revision 13975)
+++ /issm/trunk/scripts/BinRead.py	(revision 13975)
@@ -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/scripts/mToPy.py
===================================================================
--- /issm/trunk/scripts/mToPy.py	(revision 13975)
+++ /issm/trunk/scripts/mToPy.py	(revision 13975)
@@ -0,0 +1,52 @@
+#!/usr/bin/env python
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#
+program =               'mToPy.py'
+version =               '1.0'
+versionReleaseDate =    '09/24/12'
+origAuthor =            'Mike Pellegrin'
+desc = '\nMain control unit for converting an matlab script file to python'
+#
+#   Note: Output will be put in the same (absolute) location as the input.
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#				History
+#	Date		Developer           Modification
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#	09/24/12	Michael Pellegrin	Initial Release         V1.0
+#
+#
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+import sys, os, shutil
+import translateToPy
+import mToPy   # touch mToPy to assertain location of installation
+
+def convert ( inputFile ):
+    try:
+      if os.path.exists( inputFile + '.m') and os.path.isfile( inputFile + '.m'):
+        checkBackupOutputFile( inputFile )
+        convertMToPy( inputFile )
+      else:
+        print 'Specified input file: ' + inputFile + '.m doesn\'t appear to exist'
+    finally:
+      print ''
+
+def convertMToPy ( inputFileName ):
+    translateToPy.convertToPython ( inputFileName + '.m', inputFileName + '.py' )
+
+def checkBackupOutputFile ( inputFile ):
+    mFile = inputFile + '.m'
+    pyFile = inputFile + '.py'
+    if os.path.exists( pyFile ):
+        i=1
+        bkupName = pyFile + str(i)
+        while os.path.exists( bkupName ):
+            i+=1
+            bkupName = pyFile + str(i)
+        os.rename( pyFile, bkupName )
+
+    shutil.copyfile(mFile, pyFile)
+
+if __name__ == "__main__":
+    convert( sys.argv[1])
+
Index: /issm/trunk/scripts/report.sh
===================================================================
--- /issm/trunk/scripts/report.sh	(revision 13974)
+++ /issm/trunk/scripts/report.sh	(revision 13975)
@@ -10,6 +10,6 @@
 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"'
+CODE_STYLE='width="700px" rules=none'
+CODE_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;"'
@@ -104,5 +104,5 @@
 <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>"
+echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all tests have been run</span></td></tr>"
 else
 	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Matlab crashed</span></td></tr>"
@@ -133,5 +133,5 @@
 <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>"
+	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#008000\">all tests have been run</span></td></tr>"
 else
 	echo "<tr><td $BODY_FONTL>Status: <span style=\"color:#ff0000\">Python crashed</span></td></tr>"
@@ -215,5 +215,5 @@
 	<th $BODY_FONT>Field checked</th>
 	</tr>
-	$(cat matlab_short.log | while read line
+	$(cat python_short.log | while read line
 do
 	echo "<tr>"
@@ -263,5 +263,5 @@
 cat << END >> report.html
 <table $SECTION_STYLE><tr><td $SECTION_FONT>Matlab errors</td></tr></table>
-<table $MATLAB_STYLE><tr><td $MATLAB_FONT>
+<table $CODE_STYLE><tr><td $CODE_FONT>
 <pre style="
 white-space: -moz-pre-wrap;
@@ -275,9 +275,25 @@
 #}}}
 fi
+if [ $IS_PYTHON -eq 1 ] && [ -s pythonerror.log ]; then
+	#Python {{{
+	cat << END >> report.html
+<table $SECTION_STYLE><tr><td $SECTION_FONT>Python errors</td></tr></table>
+<table $CODE_STYLE><tr><td $CODE_FONT>
+<pre style="
+white-space: -moz-pre-wrap;
+white-space: -pre-wrap;
+white-space: -o-pre-wrap;
+white-space: pre-wrap;
+word-wrap: break-word;
+">$(cat pythonerror.log)</pre>
+</td></tr></table>
+END
+	#}}}
+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>
+<table $CODE_STYLE><tr><td $CODE_FONT>
 <pre style="
 white-space: -moz-pre-wrap;
Index: /issm/trunk/scripts/translateToPy.py
===================================================================
--- /issm/trunk/scripts/translateToPy.py	(revision 13975)
+++ /issm/trunk/scripts/translateToPy.py	(revision 13975)
@@ -0,0 +1,256 @@
+
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#
+program =               'translateToPy.py'
+version =               '1.0'
+versionReleaseDate =    '09/24/12'
+origAuthor =            'Mike Pellegrin'
+desc = '\nMatlab script conversion into python'
+#
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#				History
+#	Date		Developer           Modification
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+#	09/24/12 Michael Pellegrin	Initial Release     V1.0
+#
+#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+import codecs, unicodedata
+import sys, re, datetime, os
+import decimal, operator
+
+
+outputLocation = sys.stdout
+inputFile = ""
+
+# other global vars
+indentLevel = 0
+
+
+def setupOutputLocation ( outFile ):
+    if outFile != sys.stdout:
+		globals()['outputLocation'] = open( outFile, 'w' ) # clobber
+
+def translateFile ( inputFile ):
+	f = codecs.open( inputFile, encoding='utf-8' )
+	try:
+		for line in f:
+			# print "in: " +line
+
+			asciiLine = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
+			line = asciiLine
+
+			translateLine( line )
+
+	finally:
+		f.close()
+
+def translateLine ( line ):
+
+	if len(line) == 1:	# blank line
+		output( line )
+
+	elif line.split()[0][0] == '%':		# comment line
+		output("# " + line.replace('%','') )
+
+	else:		# needs cleanup.  this is a real-quick-n-dirty implimentation
+		#print line
+		res = line.replace('{','[')
+		res = res.replace('}',']')
+		res = res.replace('model','model()')
+		res = res.replace('SolutionEnum','SolutionEnum()')
+		res = res.replace('StressTensorEnum','StressTensorEnum()')
+		res = res.replace('.par','.py')
+		res = res.replace('=extrude(md,','.extrude(')
+
+		res = res.replace('thickness(pos)','thickness[pos]')
+		res = res.replace('find(md.','numpy.nonzero(md.')
+
+		res = res.replace('\n','')
+
+		# handle inline comments
+		res = res.replace('%','#')
+
+		res = res.replace('...','\\')
+
+		# determine if the m file has mult. line cmd (real quick solution)
+		multCmds = res.split(';')
+		numLines = len( multCmds ) - 2
+		allParts = ''
+		for part in multCmds:
+			allParts += part
+			#allParts += re.sub('^\s+','',part)
+			#allParts += part.strip()
+			if numLines > 0:
+				allParts += '\n'
+				numLines -= 1
+		res = allParts	
+
+		res = res.replace(';','')
+
+
+		res = convertFieldValues( res )
+		#print 'resulting line:' + str(res) + '\n'
+		output(res)
+
+def convertFieldValues ( currentLine ):
+	# before utilizing regex's {starting w/ eg. \([0-9]\) } for special case: ...(#)...
+	# i noticed what i'm looking for is only TransientSolution(*). So, ...
+
+	res = currentLine
+	if 'md.results' in currentLine:
+		res = res.replace('(md.results.','md.results[\'')
+
+		if 'TransientSolution(' in currentLine:		# got a TransientSolution([0-9..]) case
+			res = res.replace('TransientSolution(','TransientSolution\'][')
+			parts = res.split(')')
+			res = parts[0] + '][\'' + parts[1].replace('.','') + '\']' + parts[2]
+
+		else:				# handle the other cases for md.results
+			
+			res = res.replace('Solution.Vx)','Solution\'][1][\'Vx\']')
+			res = res.replace('Solution.Vy)','Solution\'][1][\'Vy\']')
+			res = res.replace('Solution.Vz)','Solution\'][1][\'Vz\']')
+			res = res.replace('Solution.Vel)','Solution\'][1][\'Vel\']')
+
+			res = res.replace('Solution.Pressure)','Solution\'][1][\'Pressure\']')
+
+			res = res.replace('Solution.StressTensorxx)','Solution\'][1][\'StressTensorxx\']')
+			res = res.replace('Solution.StressTensorxy)','Solution\'][1][\'StressTensorxy\']')
+			res = res.replace('Solution.StressTensoryy)','Solution\'][1][\'StressTensoryy\']')
+			res = res.replace('Solution.StressTensorzz)','Solution\'][1][\'StressTensorzz\']')
+			res = res.replace('Solution.StressTensorxz)','Solution\'][1][\'StressTensorxz\']')
+			res = res.replace('Solution.StressTensoryz)','Solution\'][1][\'StressTensoryz\']')
+
+			res = res.replace('Solution.FrictionCoefficient)','Solution\'][1][\'FrictionCoefficient\']')
+			res = res.replace('Solution.SurfaceforcingsMasBalance)','Solution\'][1][\'SurfaceforcingsMasBalance\']')
+			res = res.replace('Solution.MaskElementonfloatingice)','Solution\'][1][\'MaskElementonfloatingice\']')
+			res = res.replace('Solution.J)','Solution\'][1][\'J\']')
+			res = res.replace('Solution.BalancethicknessThickeningRate)','Solution\'][1][\'BalancethicknessThickeningRate\']')
+
+			res = res.replace('Solution.Gradient1)','Solution\'][1][\'Gradient1\']')
+			res = res.replace('Solution.Gradient2)','Solution\'][1][\'Gradient2\']')
+
+			res = res.replace('Solution.MaterialsRheologyZbar)','Solution\'][1][\'MaterialsRheologyZbar\']')
+			res = res.replace('Solution.MaterialsRheologyBbar)','Solution\'][1][\'MaterialsRheologyBbar\']')
+			res = res.replace('Solution.MaterialsRheologyB)','Solution\'][1][\'MaterialsRheologyB\']')
+
+			res = res.replace('Solution.Thickness)','Solution\'][1][\'Thickness\']')
+
+			res = res.replace('Solution.Temperature)','Solution\'][1][\'Temperature\']')
+
+			res = res.replace('Solution.BasalforcingsMeltingRate)','Solution\'][1][\'BasalforcingsMeltingRate\']')
+
+			res = res.replace('Solution.SurfaceSlopeX)','Solution\'][1][\'SurfaceSlopeX\']')
+			res = res.replace('Solution.SurfaceSlopeY)','Solution\'][1][\'SurfaceSlopeY\']')
+			res = res.replace('Solution.SurfaceSlopeZ)','Solution\'][1][\'SurfaceSlopeZ\']')
+
+			res = res.replace('Solution.BedSlopeX)','Solution\'][1][\'BedSlopeX\']')
+			res = res.replace('Solution.BedSlopeY)','Solution\'][1][\'BedSlopeY\']')
+			res = res.replace('Solution.BedSlopeZ)','Solution\'][1][\'BedSlopeZ\']')
+
+			res = res.replace('Solution.Enthalpy)','Solution\'][1][\'Enthalpy\']')
+			res = res.replace('Solution.Waterfraction)','Solution\'][1][\'Waterfraction\']')
+			res = res.replace('Solution.Temperature)','Solution\'][1][\'Temperature\']')
+
+			# special case
+			res = res.replace('.DiagnosticSolution.J','[\'DiagnosticSolution\'][1][\'J\']')
+
+	return res
+
+def output ( line ):
+	numTabs = indentLevel
+	while numTabs:
+		numTabs -= 1
+		print >> outputLocation, '\t',
+	print >> outputLocation, line
+
+def outputTopOfSript( inputFile ):
+
+	global indentLevel
+
+	output("\"\"\"")
+	output("== == == == == == == == == == == == == == == == == == ==")
+	output("Auto generated python script for ISSM:   %s" % (inputFile) )
+	output("Created on %s via %s Ver %s by %s" % ( datetime.date.today(), program, version, os.getlogin()))
+	output("== == == == == == == == == == == == == == == == == == ==")
+	#output("")
+	output(desc)
+	output("%s Author: Michael Pellegrin" % (program))
+	output("%s Date: %s" % (program, versionReleaseDate))
+	output("== == == == == == == == == == == == == == == == == == ==")
+	output("\"\"\"")
+	output("")
+
+def outputBottomOfScript():
+
+	global indentLevel
+
+	output("")
+	
+def genericImports ():
+	output("from MatlabFuncs import *")
+	output("from model import *")
+	output("from EnumDefinitions import *")
+	output("from numpy import *")
+
+def createImports ( inputFile ):
+	genericImports()
+
+	# cycle through eachline to assertain import needs
+	f = codecs.open( inputFile, encoding='utf-8' )
+	try:
+		for line in f:
+			# print "in: " +line
+
+			# toss blank lines
+			if len(line) == 1:
+				continue
+
+			asciiLine = unicodedata.normalize('NFKD', line).encode('ascii','ignore')
+			line = asciiLine
+
+			for il in importList:
+				if line.find(il) != -1:
+					output( "from %s import *" % (il) )
+					importList.remove(il)	# already got it
+
+	finally:
+		output("")
+		f.close()
+
+
+def initImportList ():
+	global importList
+	
+	importList = [ \
+		'triangle'	,\
+		'setmask'	,\
+		'parameterize'	,\
+		'setflowequation'	,\
+		'meshconvert'	,\
+		'solve'	,\
+		#'zeros'					# -> numpy
+		]
+	
+
+
+def convertToPython ( inFile, outFile = sys.stdout ):
+    #print ' in cnvrt to python w/ file:' + inFile
+    initImportList()
+    setupOutputLocation( outFile )
+    outputTopOfSript( inFile )
+    createImports( inFile )
+    translateFile( inFile )
+    #    outputBottomOfScript()
+
+	
+if __name__ == "__main__":
+    #print ' in main w/ arg:' + sys.argv[1]+' '+sys.argv[2]
+    if len(sys.argv)==2:
+        convertToPython( sys.argv[1], sys.argv[2] )
+    else:
+        convertToPython( sys.argv[1] )
+
+
+
Index: /issm/trunk/src/Makefile.am
===================================================================
--- /issm/trunk/src/Makefile.am	(revision 13974)
+++ /issm/trunk/src/Makefile.am	(revision 13975)
@@ -1,2 +1,5 @@
-EXTRA_DIST =  perl pro py
-SUBDIRS = c modules m
+EXTRA_DIST =  perl pro
+SUBDIRS = c m wrappers 
+if ANDROID
+SUBDIRS += android
+endif
Index: /issm/trunk/src/ad/todo
===================================================================
--- /issm/trunk/src/ad/todo	(revision 13974)
+++ /issm/trunk/src/ad/todo	(revision 13975)
@@ -57,2 +57,9 @@
 - make gdb wrapper.
 - think about ModelProcessor setup. need to keep track, before we partition, on cpu 0, of the independent declarations. 
+
+
+MPI: what's missing that equivalent of MPI.h -> no well defined api.  
+What's exposed is the internals of it.
+
+Wanted to look at changing the way for the matrices and vertices would be implemented.
+
Index: /issm/trunk/src/android/ISSM/.classpath
===================================================================
--- /issm/trunk/src/android/ISSM/.classpath	(revision 13975)
+++ /issm/trunk/src/android/ISSM/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/ISSM/.project
===================================================================
--- /issm/trunk/src/android/ISSM/.project	(revision 13975)
+++ /issm/trunk/src/android/ISSM/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>ISSM</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/ISSM/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/ISSM/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="15"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSM"
+            android:label="@string/title_activity_issm" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/ISSM/Makefile.am
===================================================================
--- /issm/trunk/src/android/ISSM/Makefile.am	(revision 13975)
+++ /issm/trunk/src/android/ISSM/Makefile.am	(revision 13975)
@@ -0,0 +1,15 @@
+EXTRA_DIST =  AndroidManifest.xml  assets gen jni obj project.properties src Makefile.am bin ic_launcher-web.png libs proguard-project.txt res
+
+#Generate JNI library using the ndk-build capabilities:
+if SHAREDLIBS 	 	 
+deps = 	 	 
+else 	 	 
+deps = ../../c/libISSMCore.a 	 	 
+endif
+
+install-exec-am: all
+all: libs/armeabi/libIssmJni.so
+
+libs/armeabi/libIssmJni.so:  $(deps)
+	$(ANDROID_NDK_DIR)/ndk-build -C ./jni clean
+	$(ANDROID_NDK_DIR)/ndk-build -C ./jni
Index: /issm/trunk/src/android/ISSM/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/ISSM/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="15"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSM"
+            android:label="@string/title_activity_issm" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/ISSM/gen/com/example/issm/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/ISSM/gen/com/example/issm/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM/gen/com/example/issm/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.issm;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/ISSM/gen/com/example/issm/R.java
===================================================================
--- /issm/trunk/src/android/ISSM/gen/com/example/issm/R.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM/gen/com/example/issm/R.java	(revision 13975)
@@ -0,0 +1,43 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.issm;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class dimen {
+        public static final int padding_large=0x7f040002;
+        public static final int padding_medium=0x7f040001;
+        public static final int padding_small=0x7f040000;
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int button1=0x7f080001;
+        public static final int input=0x7f080000;
+        public static final int menu_settings=0x7f080003;
+        public static final int output=0x7f080002;
+    }
+    public static final class layout {
+        public static final int activity_issm=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_issm=0x7f070000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f050000;
+        public static final int hello_world=0x7f050001;
+        public static final int menu_settings=0x7f050002;
+        public static final int title_activity_issm=0x7f050003;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f060000;
+    }
+}
Index: /issm/trunk/src/android/ISSM/jni/Android.mk
===================================================================
--- /issm/trunk/src/android/ISSM/jni/Android.mk	(revision 13975)
+++ /issm/trunk/src/android/ISSM/jni/Android.mk	(revision 13975)
@@ -0,0 +1,19 @@
+LOCAL_PATH:= $(call my-dir)
+my_LOCAL_PATH:=$(LOCAL_PATH)
+
+#include $(LOCAL_PATH)/issmlib\Android.mk
+include $(call all-subdir-makefiles)
+
+
+LOCAL_PATH := $(my_LOCAL_PATH)
+
+include $(CLEAR_VARS)
+LOCAL_PATH := $(my_LOCAL_PATH)
+LOCAL_ALLOW_UNDEFINED_SYMBOLS := true
+LOCAL_CFLAGS := -Wno-psabi
+LOCAL_LDLIBS := -llog -ldl
+LOCAL_MODULE := IssmJni
+LOCAL_SRC_FILES := Main.cpp 
+LOCAL_STATIC_LIBRARIES := libISSMCore
+
+include $(BUILD_SHARED_LIBRARY)
Index: /issm/trunk/src/android/ISSM/jni/Main.cpp
===================================================================
--- /issm/trunk/src/android/ISSM/jni/Main.cpp	(revision 13975)
+++ /issm/trunk/src/android/ISSM/jni/Main.cpp	(revision 13975)
@@ -0,0 +1,40 @@
+#include <jni.h>
+#include "../../../c/android/fac.h"
+namespace com_example_issm
+{
+	static jlong factorial(JNIEnv *env, jclass clazz, jlong n)
+	{
+		fac *f = new fac();
+		jlong result = (jlong) (f->factorial(n));
+		delete(f);
+		return (jlong) result;
+	}
+//------------------------------------------------------------------------------------
+	static JNINativeMethod method_table[] = {
+			{"fac" ,"(J)J" , (void *) factorial},
+	};
+}
+
+using namespace com_example_issm;
+
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
+{
+    JNIEnv* env;
+    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+        return -1;
+    }
+    else
+    {
+    	jclass clazz = env->FindClass("com/example/issm/IssmJni");
+    	if(clazz)
+    	{
+    		env->RegisterNatives(clazz, method_table, 1);
+    		env->DeleteLocalRef(clazz);
+    		return JNI_VERSION_1_6;
+    	}
+    	else return -1;
+    }
+
+    // Get jclass with env->FindClass.
+    // Register methods with env->RegisterNatives.
+}
Index: /issm/trunk/src/android/ISSM/jni/issmlib/Android.mk
===================================================================
--- /issm/trunk/src/android/ISSM/jni/issmlib/Android.mk	(revision 13975)
+++ /issm/trunk/src/android/ISSM/jni/issmlib/Android.mk	(revision 13975)
@@ -0,0 +1,6 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+LOCAL_MODULE    := libISSMCore
+LOCAL_SRC_FILES := ../../../../c/libISSMCore.a
+LOCAL_EXPORT_C_INCLUDES := ../../../../c/android/
+include $(PREBUILT_STATIC_LIBRARY)
Index: /issm/trunk/src/android/ISSM/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/ISSM/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/ISSM/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/ISSM/project.properties
===================================================================
--- /issm/trunk/src/android/ISSM/project.properties	(revision 13975)
+++ /issm/trunk/src/android/ISSM/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-15
Index: /issm/trunk/src/android/ISSM/res/layout/activity_issm.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/layout/activity_issm.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/layout/activity_issm.xml	(revision 13975)
@@ -0,0 +1,33 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" >
+
+    <EditText
+        android:id="@+id/input"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:ems="10"
+        android:inputType="number" />
+
+    <Button
+        android:id="@+id/button1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignRight="@+id/input"
+        android:layout_below="@+id/input"
+        android:layout_marginRight="46dp"
+        android:layout_marginTop="23dp"
+        android:text="calculate" />
+
+    <TextView
+        android:id="@+id/output"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/button1"
+        android:layout_marginTop="39dp"
+        android:textSize="20sp" />
+
+</RelativeLayout>
Index: /issm/trunk/src/android/ISSM/res/menu/activity_issm.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/menu/activity_issm.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/menu/activity_issm.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/ISSM/res/values-large/dimens.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values-large/dimens.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values-large/dimens.xml	(revision 13975)
@@ -0,0 +1,7 @@
+<resources>
+
+    <dimen name="padding_small">8dp</dimen>
+    <dimen name="padding_medium">16dp</dimen>
+    <dimen name="padding_large">16dp</dimen>
+
+</resources>
Index: /issm/trunk/src/android/ISSM/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM/res/values/dimens.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values/dimens.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values/dimens.xml	(revision 13975)
@@ -0,0 +1,7 @@
+<resources>
+
+    <dimen name="padding_small">8dp</dimen>
+    <dimen name="padding_medium">8dp</dimen>
+    <dimen name="padding_large">16dp</dimen>
+
+</resources>
Index: /issm/trunk/src/android/ISSM/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,8 @@
+<resources>
+
+    <string name="app_name">ISSM</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_issm">ISSM</string>
+
+</resources>
Index: /issm/trunk/src/android/ISSM/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM/src/com/example/issm/ISSM.java
===================================================================
--- /issm/trunk/src/android/ISSM/src/com/example/issm/ISSM.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM/src/com/example/issm/ISSM.java	(revision 13975)
@@ -0,0 +1,39 @@
+package com.example.issm;
+
+import android.os.Bundle;
+import android.app.Activity;
+import android.text.TextUtils;
+import android.view.Menu;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+
+
+public class ISSM extends Activity implements OnClickListener {
+	private EditText input;
+	private TextView output;
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_issm);
+        this.input  = (EditText) super.findViewById(R.id.input);
+        this.output  = (TextView) super.findViewById(R.id.output);
+        Button button = (Button) super.findViewById(R.id.button1);
+        button.setOnClickListener(this);
+        
+    }
+    
+	public void onClick(View view) 
+	{
+		// TODO Auto-generated method stub
+		String input = this.input.getText().toString();
+		if(TextUtils.isEmpty(input))
+		{
+			return;
+		}
+		long result = IssmJni.facIterative(Long.parseLong(input));
+		this.output.setText("Result = " + result + "\n");
+	}
+}
Index: /issm/trunk/src/android/ISSM/src/com/example/issm/IssmJni.java
===================================================================
--- /issm/trunk/src/android/ISSM/src/com/example/issm/IssmJni.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM/src/com/example/issm/IssmJni.java	(revision 13975)
@@ -0,0 +1,13 @@
+package com.example.issm;
+
+public class IssmJni
+{
+	public static native long fac(long n);
+	static {
+        System.loadLibrary("IssmJni");
+    }
+	public static long facIterative(long n)
+	{
+		return fac(n);
+	}
+}
Index: /issm/trunk/src/android/ISSM_Visual/.classpath
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/.classpath	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/ISSM_Visual/.project
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/.project	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>ISSM_Visual</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/ISSM_Visual/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm_visual"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSMVisual"
+            android:label="@string/title_activity_issmvisual" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/ISSM_Visual/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm_visual"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSMVisual"
+            android:label="@string/title_activity_issmvisual" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/ISSM_Visual/bin/jarlist.cache
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/bin/jarlist.cache	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/bin/jarlist.cache	(revision 13975)
@@ -0,0 +1,3 @@
+# cache for current jar dependecy. DO NOT EDIT.
+# format is <lastModified> <length> <SHA-1> <path>
+# Encoding is UTF-8
Index: /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.issm_visual;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/R.java
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/R.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/gen/com/example/issm_visual/R.java	(revision 13975)
@@ -0,0 +1,40 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.issm_visual;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int frame=0x7f070003;
+        public static final int menu_settings=0x7f070005;
+        public static final int relativeLay=0x7f070000;
+        public static final int seekBar=0x7f070001;
+        public static final int status=0x7f070002;
+        public static final int value=0x7f070004;
+    }
+    public static final class layout {
+        public static final int activity_issmvisual=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_issmvisual=0x7f060000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040000;
+        public static final int hello_world=0x7f040001;
+        public static final int menu_settings=0x7f040002;
+        public static final int title_activity_issmvisual=0x7f040003;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f050000;
+    }
+}
Index: /issm/trunk/src/android/ISSM_Visual/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/ISSM_Visual/project.properties
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/project.properties	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
Index: /issm/trunk/src/android/ISSM_Visual/res/layout/activity_issmvisual.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/layout/activity_issmvisual.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/layout/activity_issmvisual.xml	(revision 13975)
@@ -0,0 +1,46 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/relativeLay"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="horizontal" >
+
+    <SeekBar
+        android:id="@+id/seekBar"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentLeft="true"
+        android:layout_marginBottom="41dp" />
+
+    <TextView
+        android:id="@+id/status"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/seekBar"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp"
+        android:text="Status: " />
+
+    <FrameLayout
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        xmlns:tools="http://schemas.android.com/tools"
+        android:id="@+id/frame"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/value"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp" >
+    </FrameLayout>
+
+    <TextView
+        android:id="@+id/value"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/status"
+        android:layout_alignRight="@+id/status"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp"
+        android:text="Value: " />
+
+</RelativeLayout>
Index: /issm/trunk/src/android/ISSM_Visual/res/menu/activity_issmvisual.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/menu/activity_issmvisual.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/menu/activity_issmvisual.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/ISSM_Visual/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM_Visual/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM_Visual/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,8 @@
+<resources>
+
+    <string name="app_name">ISSM_Visual</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_issmvisual">ISSMVisual</string>
+
+</resources>
Index: /issm/trunk/src/android/ISSM_Visual/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/ISSMVisual.java
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/ISSMVisual.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/ISSMVisual.java	(revision 13975)
@@ -0,0 +1,99 @@
+package com.example.issm_visual;
+
+
+import android.app.Activity;
+import android.content.Context;
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+import android.opengl.GLSurfaceView.Renderer;
+import android.os.Bundle;
+import android.util.AttributeSet;
+import android.view.Menu;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.RelativeLayout;
+import android.widget.SeekBar;
+import android.widget.SeekBar.OnSeekBarChangeListener;
+import android.widget.TextView;
+import android.widget.Toast;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;	 
+import java.nio.ShortBuffer;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10; 
+
+public class ISSMVisual extends Activity implements OnSeekBarChangeListener
+{
+	private SeekBar bar;
+    private TextView txtStatus, txtValue;
+    private GLSurfaceView mGLView;
+	private FrameLayout frame;
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_issmvisual);
+        
+        bar = (SeekBar)findViewById(R.id.seekBar); // make seekbar object
+        bar.setOnSeekBarChangeListener(this); // set seekbar listener
+        txtValue = (TextView)findViewById(R.id.value);
+        txtStatus = (TextView)findViewById(R.id.status);
+        
+        mGLView = new MyGLSurfaceView(this);
+        frame = (FrameLayout)findViewById(R.id.frame);
+        frame.addView(mGLView);
+    }
+
+
+	@Override
+    public void onProgressChanged(SeekBar seekBar, int val,
+    		boolean fromUser) 
+    {
+    	// change progress text label with current Seekbar value
+    	txtValue.setText("Value: " + val);
+    	txtStatus.setText("Status: changing");
+    }
+	
+    @Override
+    public void onStartTrackingTouch(SeekBar seekBar) 
+    {
+    	txtStatus.setText("Status: Starting to track touch");
+
+    }
+    
+    @Override
+    public void onStopTrackingTouch(SeekBar seekBar) 
+    {
+    	seekBar.setSecondaryProgress(seekBar.getProgress()); // set the shade of the previous value.
+    	txtStatus.setText("Status: Ended tracking touch");
+    }
+    
+    @Override
+    protected void onPause() {
+        super.onPause();
+        // The following call pauses the rendering thread.
+        // If your OpenGL application is memory intensive,
+        // you should consider de-allocating objects that
+        // consume significant memory here.
+        mGLView.onPause();
+    }
+    
+    @Override
+    protected void onResume() {
+        super.onResume();
+        // The following call resumes a paused rendering thread.
+        // If you de-allocated graphic objects for onPause()
+        // this is a good place to re-allocate them.
+        mGLView.onResume();
+    }
+
+    
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) 
+    {
+        getMenuInflater().inflate(R.menu.activity_issmvisual, menu);
+        return true;
+    }
+}
Index: /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLRenderer.java
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLRenderer.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLRenderer.java	(revision 13975)
@@ -0,0 +1,248 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.issm_visual;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+
+public class MyGLRenderer implements GLSurfaceView.Renderer {
+
+    private Triangle mTriangle1, mTriangle2, mTriangle3;
+
+    @Override
+    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+
+        // Set the background frame color
+        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
+
+        mTriangle1 = new Triangle(
+        0.0f,  0.6f, 0.0f,   // top
+       -0.5f, -0.3f, 0.0f,   // bottom left
+        0.5f, -0.3f, 0.0f,
+        0.0f, 0.0f, 1.0f, 1.0f);   // bottom right
+        //mTriangle = new Triangle();
+        
+        mTriangle2 = new Triangle(
+        -0.5f, -0.3f, 0.0f,
+         0.0f, -1.0f, 0.0f,
+         0.5f,  -0.3f, 0.0f,
+         1.0f, 0.0f, 0.0f, 1.0f);
+        
+        mTriangle3 = new Triangle(
+        0.0f,  0.6f, 0.0f,
+        0.5f, -0.3f, 0.0f,
+        1.0f,  0.6f, 0.0f,
+        1.0f, 1.0f, 0.0f, 1.0f);
+    }
+
+    @Override
+    public void onDrawFrame(GL10 unused) {
+
+        // Draw background color
+        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+
+        // Draw triangle
+        mTriangle1.draw(); 
+        mTriangle2.draw();
+        mTriangle3.draw();
+    }
+
+    @Override
+    public void onSurfaceChanged(GL10 unused, int width, int height) {
+        // Adjust the viewport based on geometry changes,
+        // such as screen rotation
+        GLES20.glViewport(0, 0, width, height);
+    }
+
+    public static int loadShader(int type, String shaderCode){
+
+        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
+        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
+        int shader = GLES20.glCreateShader(type);
+
+        // add the source code to the shader and compile it
+        GLES20.glShaderSource(shader, shaderCode);
+        GLES20.glCompileShader(shader);
+
+        return shader;
+    }
+
+}
+
+class Triangle 
+{
+
+    private final String vertexShaderCode =
+        "attribute vec4 vPosition;" +
+        "void main() {" +
+        "  gl_Position = vPosition;" +
+        "}";
+
+    private final String fragmentShaderCode =
+        "precision mediump float;" +
+        "uniform vec4 vColor;" +
+        "void main() {" +
+        "  gl_FragColor = vColor;" +
+        "}";
+
+    private final FloatBuffer vertexBuffer;
+    private final int mProgram;
+    private int mPositionHandle;
+    private int mColorHandle;
+
+    // number of coordinates per vertex in this array
+    static final int COORDS_PER_VERTEX = 3;
+    float triangleCoords[] ; /*){ // in counterclockwise order:
+         0.0f,  0.6f, 0.0f,   // top
+        -0.5f, -0.3f, 0.0f,   // bottom left
+         0.5f, -0.3f, 0.0f};  */ // bottom right
+         
+        /* -0.55f, -0.35f, 0.0f,
+         0.0f, -1.2f, 0.0f,
+         0.55f,  -0.35f, 0.0f
+    };*/
+    
+    private final int vertexCount = 9 / COORDS_PER_VERTEX;
+    private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex
+
+    // Set color with red, green, blue and alpha (opacity) values
+    float color[];
+    //private final FloatBuffer colorBuffer;
+    private final int colorCount = 4/COORDS_PER_VERTEX;
+    
+    public Triangle() 
+    {
+        // initialize vertex byte buffer for shape coordinates
+        ByteBuffer bb = ByteBuffer.allocateDirect(
+                // (number of coordinate values * 4 bytes per float)
+                triangleCoords.length * 4);
+        // use the device hardware's native byte order
+        bb.order(ByteOrder.nativeOrder());
+
+        // create a floating point buffer from the ByteBuffer
+        vertexBuffer = bb.asFloatBuffer();
+        // add the coordinates to the FloatBuffer
+        vertexBuffer.put(triangleCoords);
+        // set the buffer to read the first coordinate
+        vertexBuffer.position(0);
+
+        /*ByteBuffer bb1 = ByteBuffer.allocateDirect(color.length*4);
+        bb1.order(ByteOrder.nativeOrder());
+        colorBuffer = bb1.asFloatBuffer();
+        colorBuffer.put(color);
+        colorBuffer.position(0);*/
+        
+        //GLES20.glEnableVertexAttribArray(1);
+        //GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, colorBuffer);
+        
+        // prepare shaders and OpenGL program
+        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
+                                                   vertexShaderCode);
+        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
+                                                     fragmentShaderCode);
+
+        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
+        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
+        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
+        GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables
+    }
+    public Triangle(float x1, float y1, float z1,
+    			    float x2, float y2, float z2,
+    			    float x3, float y3, float z3,
+    			    float c1, float c2, float c3, float c4) 
+    {
+    	triangleCoords = new float[9];
+    	color = new float[4];
+    	triangleCoords[0] = x1;
+    	triangleCoords[1] = y1;
+    	triangleCoords[2] = z1;
+    	triangleCoords[3] = x2;
+    	triangleCoords[4] = y2;
+    	triangleCoords[5] = z2;
+    	triangleCoords[6] = x3;
+    	triangleCoords[7] = y3;
+    	triangleCoords[8] = z3;
+    	color[0] = c1;
+    	color[1] = c2;
+    	color[2] = c3;
+    	color[3] = c4;
+        // initialize vertex byte buffer for shape coordinates
+        ByteBuffer bb = ByteBuffer.allocateDirect(
+                // (number of coordinate values * 4 bytes per float)
+                triangleCoords.length * 4);
+        // use the device hardware's native byte order
+        bb.order(ByteOrder.nativeOrder());
+
+        // create a floating point buffer from the ByteBuffer
+        vertexBuffer = bb.asFloatBuffer();
+        // add the coordinates to the FloatBuffer
+        vertexBuffer.put(triangleCoords);
+        // set the buffer to read the first coordinate
+        vertexBuffer.position(0);
+
+        /*ByteBuffer bb1 = ByteBuffer.allocateDirect(color.length*4);
+        bb1.order(ByteOrder.nativeOrder());
+        colorBuffer = bb1.asFloatBuffer();
+        colorBuffer.put(color);
+        colorBuffer.position(0);*/
+           
+        // prepare shaders and OpenGL program
+        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
+                                                   vertexShaderCode);
+        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
+                                                     fragmentShaderCode);
+
+        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
+        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
+        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
+        GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables
+    }
+
+    public void draw() 
+    {
+        // Add program to OpenGL environment
+        GLES20.glUseProgram(mProgram);
+
+        // get handle to vertex shader's vPosition member
+        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
+
+        // Enable a handle to the triangle vertices
+        GLES20.glEnableVertexAttribArray(mPositionHandle);
+
+        // Prepare the triangle coordinate data
+        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
+                                     GLES20.GL_FLOAT, false,
+                                     vertexStride, vertexBuffer);
+
+        // get handle to fragment shader's vColor member
+        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
+
+        // Set color for drawing the triangle
+        //GLES20.glUniform4fv(mColorHandle, 0, color, 0);
+        //GLES20.glVertexAttrib4f(0, 0.5f, 0.5f, 0.0f, 1.0f);
+        //GLES20.glVertexAttribPointer(mPositionHandle, 4, GLES20.GL_FLOAT, false, stride, offset)
+        GLES20.glUniform4fv(mColorHandle, 1, color, 0);
+        // Draw the triangle
+        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
+    }
+}
Index: /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLSurfaceView.java
===================================================================
--- /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLSurfaceView.java	(revision 13975)
+++ /issm/trunk/src/android/ISSM_Visual/src/com/example/issm_visual/MyGLSurfaceView.java	(revision 13975)
@@ -0,0 +1,21 @@
+package com.example.issm_visual;
+
+import android.content.Context;
+import android.opengl.GLSurfaceView;
+
+
+class MyGLSurfaceView extends GLSurfaceView {
+
+    public MyGLSurfaceView(Context context) {
+        super(context);
+
+        // Create an OpenGL ES 2.0 context.
+        setEGLContextClientVersion(2);
+
+        // Set the Renderer for drawing on the GLSurfaceView
+        setRenderer(new MyGLRenderer());
+
+        // Render the view only when there is a change in the drawing data
+        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
+    }
+}
Index: /issm/trunk/src/android/Makefile.am
===================================================================
--- /issm/trunk/src/android/Makefile.am	(revision 13975)
+++ /issm/trunk/src/android/Makefile.am	(revision 13975)
@@ -0,0 +1,2 @@
+EXTRA_DIST =  Factorial Makefile.am helloworld issm-android-inputfiles two-libs
+SUBDIRS = ISSM
Index: /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.cpp
===================================================================
--- /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.cpp	(revision 13975)
+++ /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.cpp	(revision 13975)
@@ -0,0 +1,8 @@
+#include <stdio.h>
+#include <jni.h>
+#include "HelloWorld.h"
+JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
+{
+	printf("Hello World!\n");
+	return;
+}
Index: /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.h
===================================================================
--- /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.h	(revision 13975)
+++ /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.h	(revision 13975)
@@ -0,0 +1,21 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+/* Header for class HelloWorld */
+
+#ifndef _Included_HelloWorld
+#define _Included_HelloWorld
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class:     HelloWorld
+ * Method:    print
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_HelloWorld_print
+  (JNIEnv *, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
Index: /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.java
===================================================================
--- /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/HelloWorldJNI/HelloWorld.java	(revision 13975)
@@ -0,0 +1,16 @@
+class HelloWorld
+{
+	public native void print(); //native method
+	static //static initializer code
+	{
+		System.loadLibrary("CLibHelloWorld");
+	}
+}
+class Main
+{
+	public static void main (String[] args)
+	{
+		HelloWorld hw = new HelloWorld();
+		hw.print();
+	}
+}
Index: /issm/trunk/src/android/helloworld/HelloWorldJNI/Main.java
===================================================================
--- /issm/trunk/src/android/helloworld/HelloWorldJNI/Main.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/HelloWorldJNI/Main.java	(revision 13975)
@@ -0,0 +1,8 @@
+class Main
+{
+	public static void main (String[] args)
+	{
+		HelloWorld hw = new HelloWorld();
+		hw.print();
+	}
+}
Index: /issm/trunk/src/android/helloworld/ISSM/.classpath
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/.classpath	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/helloworld/ISSM/.project
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/.project	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>ISSM</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/helloworld/ISSM/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSM"
+            android:label="@string/title_activity_issm" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/ISSM/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.issm"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="5"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".ISSM"
+            android:label="@string/title_activity_issm" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/ISSM/bin/jarlist.cache
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/bin/jarlist.cache	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/bin/jarlist.cache	(revision 13975)
@@ -0,0 +1,3 @@
+# cache for current jar dependecy. DO NOT EDIT.
+# format is <lastModified> <length> <SHA-1> <path>
+# Encoding is UTF-8
Index: /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.issm;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/R.java
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/R.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/gen/com/example/issm/R.java	(revision 13975)
@@ -0,0 +1,39 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.issm;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int frame=0x7f070003;
+        public static final int menu_settings=0x7f070005;
+        public static final int relativeLay=0x7f070000;
+        public static final int seekBar=0x7f070001;
+        public static final int status=0x7f070002;
+        public static final int value=0x7f070004;
+    }
+    public static final class layout {
+        public static final int activity_issm=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_issm=0x7f060000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040000;
+        public static final int menu_settings=0x7f040001;
+        public static final int title_activity_issm=0x7f040002;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f050000;
+    }
+}
Index: /issm/trunk/src/android/helloworld/ISSM/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/helloworld/ISSM/project.properties
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/project.properties	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
Index: /issm/trunk/src/android/helloworld/ISSM/res/layout/activity_issm.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/layout/activity_issm.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/layout/activity_issm.xml	(revision 13975)
@@ -0,0 +1,46 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:id="@+id/relativeLay"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="horizontal" >
+
+    <SeekBar
+        android:id="@+id/seekBar"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentLeft="true"
+        android:layout_marginBottom="41dp" />
+
+    <TextView
+        android:id="@+id/status"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/seekBar"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp"
+        android:text="Status: " />
+
+    <FrameLayout
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        xmlns:tools="http://schemas.android.com/tools"
+        android:id="@+id/frame"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/value"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp" >
+    </FrameLayout>
+
+    <TextView
+        android:id="@+id/value"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/status"
+        android:layout_alignRight="@+id/status"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="16dp"
+        android:text="Value: " />
+
+</RelativeLayout>
Index: /issm/trunk/src/android/helloworld/ISSM/res/menu/activity_issm.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/menu/activity_issm.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/menu/activity_issm.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/helloworld/ISSM/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/ISSM/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/ISSM/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,7 @@
+<resources>
+
+    <string name="app_name">ISSM</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_issm">ISSM</string>
+
+</resources>
Index: /issm/trunk/src/android/helloworld/ISSM/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/ISSM.java
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/ISSM.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/ISSM.java	(revision 13975)
@@ -0,0 +1,97 @@
+package com.example.issm;
+
+import android.app.Activity;
+import android.content.Context;
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+import android.opengl.GLSurfaceView.Renderer;
+import android.os.Bundle;
+import android.util.AttributeSet;
+import android.view.Menu;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.RelativeLayout;
+import android.widget.SeekBar;
+import android.widget.SeekBar.OnSeekBarChangeListener;
+import android.widget.TextView;
+import android.widget.Toast;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;	 
+import java.nio.ShortBuffer;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10; 
+
+public class ISSM extends Activity implements OnSeekBarChangeListener
+{
+	private SeekBar bar;
+    private TextView txtStatus, txtValue;
+    private GLSurfaceView mGLView;
+	private FrameLayout frame;
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_issm);
+        
+        bar = (SeekBar)findViewById(R.id.seekBar); // make seekbar object
+        bar.setOnSeekBarChangeListener(this); // set seekbar listener
+        txtValue = (TextView)findViewById(R.id.value);
+        txtStatus = (TextView)findViewById(R.id.status);
+        
+        mGLView = new MyGLSurfaceView(this);
+        frame = (FrameLayout)findViewById(R.id.frame);
+        frame.addView(mGLView);
+
+    }
+
+
+	@Override
+    public void onProgressChanged(SeekBar seekBar, int val,
+    		boolean fromUser) 
+    {
+    	// change progress text label with current Seekbar value
+    	txtValue.setText("Value: " + val);
+    	txtStatus.setText("Status: changing");
+    }
+    @Override
+    public void onStartTrackingTouch(SeekBar seekBar) 
+    {
+    	txtStatus.setText("Status: Starting to track touch");
+
+    }
+    @Override
+    public void onStopTrackingTouch(SeekBar seekBar) 
+    {
+    	seekBar.setSecondaryProgress(seekBar.getProgress()); // set the shade of the previous value.
+    	txtStatus.setText("Status: Ended tracking touch");
+    }
+    
+    @Override
+    protected void onPause() {
+        super.onPause();
+        // The following call pauses the rendering thread.
+        // If your OpenGL application is memory intensive,
+        // you should consider de-allocating objects that
+        // consume significant memory here.
+        mGLView.onPause();
+    }
+    
+    @Override
+    protected void onResume() {
+        super.onResume();
+        // The following call resumes a paused rendering thread.
+        // If you de-allocated graphic objects for onPause()
+        // this is a good place to re-allocate them.
+        mGLView.onResume();
+    }
+
+    
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) 
+    {
+        getMenuInflater().inflate(R.menu.activity_issm, menu);
+        return true;
+    }
+}
Index: /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLRenderer.java
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLRenderer.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLRenderer.java	(revision 13975)
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.issm;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+
+public class MyGLRenderer implements GLSurfaceView.Renderer {
+
+    private Triangle mTriangle;
+
+    @Override
+    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+
+        // Set the background frame color
+        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
+
+        mTriangle = new Triangle();
+    }
+
+    @Override
+    public void onDrawFrame(GL10 unused) {
+
+        // Draw background color
+        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+
+        // Draw triangle
+        mTriangle.draw();
+    }
+
+    @Override
+    public void onSurfaceChanged(GL10 unused, int width, int height) {
+        // Adjust the viewport based on geometry changes,
+        // such as screen rotation
+        GLES20.glViewport(0, 0, width, height);
+    }
+
+    public static int loadShader(int type, String shaderCode){
+
+        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
+        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
+        int shader = GLES20.glCreateShader(type);
+
+        // add the source code to the shader and compile it
+        GLES20.glShaderSource(shader, shaderCode);
+        GLES20.glCompileShader(shader);
+
+        return shader;
+    }
+
+}
+
+class Triangle 
+{
+
+    private final String vertexShaderCode =
+        "attribute vec4 vPosition;" +
+        "void main() {" +
+        "  gl_Position = vPosition;" +
+        "}";
+
+    private final String fragmentShaderCode =
+        "precision mediump float;" +
+        "uniform vec4 vColor;" +
+        "void main() {" +
+        "  gl_FragColor = vColor;" +
+        "}";
+
+    private final FloatBuffer vertexBuffer;
+    private final int mProgram;
+    private int mPositionHandle;
+    private int mColorHandle;
+
+    // number of coordinates per vertex in this array
+    static final int COORDS_PER_VERTEX = 3;
+    static float triangleCoords[] = { // in counterclockwise order:
+         0.0f,  0.6f, 0.0f,   // top
+        -0.5f, -0.3f, 0.0f,   // bottom left
+         0.5f, -0.3f, 0.0f,
+         -0.5f, -0.3f, 0.0f,
+         0.0f, -1.2f, 0.0f,
+         0.5f,  -0.3f, 0.0f
+         
+         
+         
+
+
+         // bottom right
+    };
+    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
+    private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex
+
+    // Set color with red, green, blue and alpha (opacity) values
+    float color[] = { 0.0f, 0.0f, 1.0f, 1.0f}; //blue
+    float color1[] = {1.0f, 0.0f, 0.0f, 1.0f};
+
+    public Triangle() {
+        // initialize vertex byte buffer for shape coordinates
+        ByteBuffer bb = ByteBuffer.allocateDirect(
+                // (number of coordinate values * 4 bytes per float)
+                triangleCoords.length * 4);
+        // use the device hardware's native byte order
+        bb.order(ByteOrder.nativeOrder());
+
+        // create a floating point buffer from the ByteBuffer
+        vertexBuffer = bb.asFloatBuffer();
+        // add the coordinates to the FloatBuffer
+        vertexBuffer.put(triangleCoords);
+        // set the buffer to read the first coordinate
+        vertexBuffer.position(0);
+
+        // prepare shaders and OpenGL program
+        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
+                                                   vertexShaderCode);
+        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
+                                                     fragmentShaderCode);
+
+        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
+        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
+        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
+        GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables
+
+    }
+
+    public void draw() {
+        // Add program to OpenGL environment
+        GLES20.glUseProgram(mProgram);
+
+        // get handle to vertex shader's vPosition member
+        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
+
+        // Enable a handle to the triangle vertices
+        GLES20.glEnableVertexAttribArray(mPositionHandle);
+
+        // Prepare the triangle coordinate data
+        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
+                                     GLES20.GL_FLOAT, false,
+                                     vertexStride, vertexBuffer);
+
+        // get handle to fragment shader's vColor member
+        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
+
+        // Set color for drawing the triangle
+        GLES20.glUniform4fv(mColorHandle, 0, color, 0);
+        // Draw the triangle
+        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 1, vertexCount);
+        
+        
+        GLES20.glUniform4fv(mColorHandle, 0, color1, 0);
+        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
+        
+
+        // Disable vertex array
+        GLES20.glDisableVertexAttribArray(mPositionHandle);
+    }
+}
Index: /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLSurfaceView.java
===================================================================
--- /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLSurfaceView.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/ISSM/src/com/example/issm/MyGLSurfaceView.java	(revision 13975)
@@ -0,0 +1,21 @@
+package com.example.issm;
+
+import android.content.Context;
+import android.opengl.GLSurfaceView;
+
+
+class MyGLSurfaceView extends GLSurfaceView {
+
+    public MyGLSurfaceView(Context context) {
+        super(context);
+
+        // Create an OpenGL ES 2.0 context.
+        setEGLContextClientVersion(2);
+
+        // Set the Renderer for drawing on the GLSurfaceView
+        setRenderer(new MyGLRenderer());
+
+        // Render the view only when there is a change in the drawing data
+        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
+    }
+}
Index: /issm/trunk/src/android/helloworld/My First App/.classpath
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/.classpath	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/helloworld/My First App/.project
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/.project	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>My First App</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/helloworld/My First App/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.my.first.app"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/My First App/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.my.first.app"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/My First App/bin/jarlist.cache
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/bin/jarlist.cache	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/bin/jarlist.cache	(revision 13975)
@@ -0,0 +1,3 @@
+# cache for current jar dependecy. DO NOT EDIT.
+# format is <lastModified> <length> <SHA-1> <path>
+# Encoding is UTF-8
Index: /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.my.first.app;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/R.java
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/R.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/gen/com/example/my/first/app/R.java	(revision 13975)
@@ -0,0 +1,41 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.my.first.app;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int button1=0x7f070001;
+        public static final int edit_message=0x7f070000;
+        public static final int menu_settings=0x7f070005;
+        public static final int seekBar1=0x7f070002;
+        public static final int textViewAction=0x7f070004;
+        public static final int textViewProgress=0x7f070003;
+    }
+    public static final class layout {
+        public static final int activity_main=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_main=0x7f060000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040000;
+        public static final int button_send=0x7f040002;
+        public static final int edit_message=0x7f040001;
+        public static final int menu_settings=0x7f040003;
+        public static final int title_activity_main=0x7f040004;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f050000;
+    }
+}
Index: /issm/trunk/src/android/helloworld/My First App/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/helloworld/My First App/project.properties
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/project.properties	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
Index: /issm/trunk/src/android/helloworld/My First App/res/layout/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/layout/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/layout/activity_main.xml	(revision 13975)
@@ -0,0 +1,62 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="horizontal" >
+
+    <EditText
+        android:id="@+id/edit_message"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentTop="true"
+        android:layout_centerHorizontal="true"
+        android:layout_marginTop="48dp"
+        android:ems="10"
+        android:hint="@string/edit_message" />
+
+    <Button
+        android:id="@+id/button1"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentBottom="true"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="36dp"
+        android:text="@string/button_send" />
+
+    <SeekBar
+        android:id="@+id/seekBar1"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/button1"
+        android:layout_alignParentLeft="true"
+        android:layout_marginBottom="50dp" />
+
+    <TextView
+        android:id="@+id/textViewProgress"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/seekBar1"
+        android:layout_centerHorizontal="true"
+        android:layout_marginBottom="22dp"
+        android:text="progress displayed here"
+        android:textAppearance="?android:attr/textAppearanceLarge" />
+
+    <TextView
+        android:id="@+id/textViewAction"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_above="@+id/textViewProgress"
+        android:layout_alignRight="@+id/textViewProgress"
+        android:layout_marginBottom="26dp"
+        android:text="action displayed here"
+        android:textAppearance="?android:attr/textAppearanceLarge" />
+
+<!--<com.example.my.first.app.MainActivity.CustomDrawableView
+   android:id="@+id/custom_drawable_view"
+   android:layout_width="fill_parent"     
+    android:layout_height="wrap_content" /> 
+-->
+
+    
+
+</RelativeLayout>
Index: /issm/trunk/src/android/helloworld/My First App/res/menu/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/menu/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/menu/activity_main.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/helloworld/My First App/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/My First App/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/My First App/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,7 @@
+<resources>
+    <string name="app_name">My First App</string>
+    <string name="edit_message">Enter a message</string>
+    <string name="button_send">Send</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_main">MainActivity</string>
+</resources>
Index: /issm/trunk/src/android/helloworld/My First App/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/My First App/src/com/example/my/first/app/MainActivity.java
===================================================================
--- /issm/trunk/src/android/helloworld/My First App/src/com/example/my/first/app/MainActivity.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/My First App/src/com/example/my/first/app/MainActivity.java	(revision 13975)
@@ -0,0 +1,103 @@
+package com.example.my.first.app;
+
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.util.AttributeSet;
+import android.view.Menu;
+import android.view.View;
+import android.widget.SeekBar;
+import android.widget.SeekBar.OnSeekBarChangeListener;
+import android.widget.TextView;
+import android.widget.Toast;
+import android.graphics.*;
+import android.graphics.drawable.ShapeDrawable;
+import android.graphics.drawable.shapes.RectShape;
+
+public class MainActivity extends Activity implements OnSeekBarChangeListener{
+    private SeekBar bar; 
+    private TextView textProgress,textAction;
+    //CustomDrawableView mCustomDrawableView;
+        
+    /*public class CustomDrawableView extends View {
+        private ShapeDrawable mDrawable;
+        
+        public CustomDrawableView(Context context, AttributeSet attrs) {
+            super(context, attrs);
+        
+
+
+        int x = 10;
+        int y = 10;
+        int width = 300;
+        int height = 50;
+
+        mDrawable = new ShapeDrawable(new RectShape());
+        mDrawable.getPaint().setColor(0xff74AC23);
+        mDrawable.setBounds(x, y, x + width, y + height);
+        }
+
+        protected void onDraw(Canvas canvas) {
+        mDrawable.draw(canvas);
+        }
+    }*/
+    
+    @Override
+    public void onCreate(Bundle savedInstanceState) { 
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+
+        Toast.makeText(MainActivity.this,"You clicked me!", Toast.LENGTH_LONG).show();
+        bar = (SeekBar)findViewById(R.id.seekBar1); // make seekbar object
+        bar.setOnSeekBarChangeListener(this); // set seekbar listener.
+        // since we are using this class as the listener the class is "this"
+
+        // make text label for progress value
+        textProgress = (TextView)findViewById(R.id.textViewProgress);
+        // make text label for action
+        textAction = (TextView)findViewById(R.id.textViewAction);
+
+        //Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
+        //Canvas c = new Canvas(b);
+        //mCustomDrawableView = (CustomDrawableView) findViewById(R.id.custom_drawable_view);
+        
+    }
+ 
+
+    @Override
+    public void onProgressChanged(SeekBar seekBar, int progress,
+    		boolean fromUser) 
+    {
+    	// change progress text label with current seekbar value
+    	textProgress.setText("The value is: "+progress);
+    	// change action text label to changing
+    	textAction.setText("changing");
+    	//drawPoints()
+    }
+    @Override
+    public void onStartTrackingTouch(SeekBar seekBar) {
+    	// TODO Auto-generated method stub
+    	textAction.setText("starting to track touch");
+
+    }
+    @Override
+    public void onStopTrackingTouch(SeekBar seekBar) {
+    	// TODO Auto-generated method stub
+    	seekBar.setSecondaryProgress(seekBar.getProgress()); // set the shade of the previous value.
+    	textAction.setText("ended tracking touch");
+    }
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        getMenuInflater().inflate(R.menu.activity_main, menu);
+        return true;
+    }
+    
+
+
+
+
+}
+
+    
+
+
Index: /issm/trunk/src/android/helloworld/OpenGLES20/.classpath
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/.classpath	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/.project
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/.project	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>OpenGLES20</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,27 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.opengles20"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+    
+    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,27 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.opengles20"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="8"
+        android:targetSdkVersion="15" />
+    
+    <uses-feature android:glEsVersion="0x00020000" android:required="true" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".MainActivity"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.opengles20;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/R.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/R.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/gen/com/example/opengles20/R.java	(revision 13975)
@@ -0,0 +1,35 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.opengles20;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int menu_settings=0x7f070000;
+    }
+    public static final class layout {
+        public static final int activity_main=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_main=0x7f060000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040000;
+        public static final int hello_world=0x7f040001;
+        public static final int menu_settings=0x7f040002;
+        public static final int title_activity_main=0x7f040003;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f050000;
+    }
+}
Index: /issm/trunk/src/android/helloworld/OpenGLES20/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/helloworld/OpenGLES20/project.properties
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/project.properties	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/layout/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/layout/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/layout/activity_main.xml	(revision 13975)
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2012 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+  
+          http://www.apache.org/licenses/LICENSE-2.0
+  
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical" >
+
+    <TextView
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:text="hello" />
+
+</LinearLayout>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/menu/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/menu/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/menu/activity_main.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,8 @@
+<resources>
+
+    <string name="app_name">OpenGLES20</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_main">MainActivity</string>
+
+</resources>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MainActivity.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MainActivity.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MainActivity.java	(revision 13975)
@@ -0,0 +1,57 @@
+package com.example.opengles20;
+
+
+import android.app.Activity;
+import android.content.Context;
+import android.opengl.GLSurfaceView;
+import android.os.Bundle;
+
+public class MainActivity extends Activity {
+
+    private GLSurfaceView mGLView;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        // Create a GLSurfaceView instance and set it
+        // as the ContentView for this Activity.
+        mGLView = new MyGLSurfaceView(this);
+        setContentView(mGLView);
+    }
+    @Override
+    protected void onPause() {
+        super.onPause();
+        // The following call pauses the rendering thread.
+        // If your OpenGL application is memory intensive,
+        // you should consider de-allocating objects that
+        // consume significant memory here.
+        mGLView.onPause();
+    }
+    
+    @Override
+    protected void onResume() {
+        super.onResume();
+        // The following call resumes a paused rendering thread.
+        // If you de-allocated graphic objects for onPause()
+        // this is a good place to re-allocate them.
+        mGLView.onResume();
+    }
+}
+  
+class MyGLSurfaceView extends GLSurfaceView {
+
+	 public MyGLSurfaceView(Context context) {
+	        super(context);
+
+	        // Create an OpenGL ES 2.0 context.
+	        setEGLContextClientVersion(2);
+
+	        // Set the Renderer for drawing on the GLSurfaceView
+	        setRenderer(new MyGL20Renderer());
+
+	        // Render the view only when there is a change in the drawing data
+	        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
+	    }
+    
+}
Index: /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MyGL20Renderer.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MyGL20Renderer.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/MyGL20Renderer.java	(revision 13975)
@@ -0,0 +1,46 @@
+package com.example.opengles20;
+
+
+
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+import android.opengl.GLES20;
+import android.opengl.GLSurfaceView;
+
+	public class MyGL20Renderer implements GLSurfaceView.Renderer {
+	private	Triangle mTriangle;
+	//private Square mSquare;
+
+	public void onSurfaceCreated(GL10 unused, EGLConfig config) {
+	        //Set the background frame color
+	        GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
+	        mTriangle = new Triangle();
+	        //mSquare = new Square();
+	    }
+
+	    public void onDrawFrame(GL10 unused) {
+	        // Redraw background color
+	        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
+	        mTriangle.draw1();
+	        //mSquare.draw2();
+	    }
+
+	    public void onSurfaceChanged(GL10 unused, int width, int height) {
+	        GLES20.glViewport(0, 0, width, height);
+	    }
+	    
+		public static int loadShader(int type, String shaderCode){
+
+		    // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
+		    // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
+		    int shader = GLES20.glCreateShader(type);
+
+		    // add the source code to the shader and compile it
+		    GLES20.glShaderSource(shader, shaderCode);
+		    GLES20.glCompileShader(shader);
+
+		    return shader;
+		}
+	}
+	
Index: /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Square.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Square.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Square.java	(revision 13975)
@@ -0,0 +1,76 @@
+package com.example.opengles20;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+import java.nio.ShortBuffer;
+
+import android.opengl.GLES20;
+
+class Square {
+
+    private FloatBuffer vertexBuffer;
+    private ShortBuffer drawListBuffer;
+
+    // number of coordinates per vertex in this array
+    static final int COORDS_PER_VERTEX = 3;
+    static float squareCoords[] = { -0.5f,  0.5f, 0.0f,   // top left
+                                    -0.5f, -0.5f, 0.0f,   // bottom left
+                                     0.5f, -0.5f, 0.0f,   // bottom right
+                                     0.5f,  0.5f, 0.0f }; // top right
+    // Set color with red, green, blue and alpha (opacity) values
+    float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
+    private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices
+    private int mProgram; 
+    private int mPositionHandle;
+    private int mColorHandle;
+    private final int vertexCount = squareCoords.length / COORDS_PER_VERTEX;
+    private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex
+
+    public Square() {
+        // initialize vertex byte buffer for shape coordinates
+        ByteBuffer bb = ByteBuffer.allocateDirect(
+        // (# of coordinate values * 4 bytes per float)
+                squareCoords.length * 4);
+        bb.order(ByteOrder.nativeOrder());
+        vertexBuffer = bb.asFloatBuffer();
+        vertexBuffer.put(squareCoords);
+        vertexBuffer.position(0);
+
+        // initialize byte buffer for the draw list
+        ByteBuffer dlb = ByteBuffer.allocateDirect(
+        // (# of coordinate values * 2 bytes per short)
+                drawOrder.length * 2);
+        dlb.order(ByteOrder.nativeOrder());
+        drawListBuffer = dlb.asShortBuffer();
+        drawListBuffer.put(drawOrder);
+        drawListBuffer.position(0);
+    }
+    public void draw2() {
+        // Add program to OpenGL ES environment
+        GLES20.glUseProgram(mProgram);
+
+        // get handle to vertex shader's vPosition member
+        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
+
+        // Enable a handle to the triangle vertices
+        GLES20.glEnableVertexAttribArray(mPositionHandle);
+
+        // Prepare the triangle coordinate data
+        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
+                                     GLES20.GL_FLOAT, false,
+                                     vertexStride, vertexBuffer);
+
+        // get handle to fragment shader's vColor member
+        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
+
+        // Set color for drawing the triangle
+        GLES20.glUniform4fv(mColorHandle, 1, color, 0);
+
+        // Draw the triangle
+        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
+
+        // Disable vertex array
+        GLES20.glDisableVertexAttribArray(mPositionHandle);
+    }
+}
Index: /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Triangle.java
===================================================================
--- /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Triangle.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/OpenGLES20/src/com/example/opengles20/Triangle.java	(revision 13975)
@@ -0,0 +1,94 @@
+package com.example.opengles20;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.FloatBuffer;
+
+import android.opengl.GLES20;
+
+class Triangle {
+
+    private FloatBuffer vertexBuffer;
+
+    // number of coordinates per vertex in this array
+    static final int COORDS_PER_VERTEX = 3;
+    static float triangleCoords[] = { // in counterclockwise order:
+         0.0f,  0.622008459f, 0.0f,   // top
+        -0.5f, -0.311004243f, 0.0f,   // bottom left
+         0.5f, -0.311004243f, 0.0f    // bottom right
+    };
+
+    private int mProgram; 
+    private int mPositionHandle;
+    private int mColorHandle;
+    private final int vertexCount = triangleCoords.length / COORDS_PER_VERTEX;
+    private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex
+
+    // Set color with red, green, blue and alpha (opacity) values
+    float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
+    
+	private final String vertexShaderCode =
+			"attribute vec4 vPosition;" +
+			"void main() {" +
+			"  gl_Position = vPosition;" +
+			"}";
+
+	private final String fragmentShaderCode =
+			"precision mediump float;" +
+			"uniform vec4 vColor;" +
+			"void main() {" +
+			"  gl_FragColor = vColor;" +
+			"}";
+	
+
+    public Triangle() {
+        // initialize vertex byte buffer for shape coordinates
+        ByteBuffer bb = ByteBuffer.allocateDirect(
+                // (number of coordinate values * 4 bytes per float)
+                triangleCoords.length * 4);
+        // use the device hardware's native byte order
+        bb.order(ByteOrder.nativeOrder());
+
+        // create a floating point buffer from the ByteBuffer
+        vertexBuffer = bb.asFloatBuffer();
+        // add the coordinates to the FloatBuffer
+        vertexBuffer.put(triangleCoords);
+        // set the buffer to read the first coordinate
+        vertexBuffer.position(0);
+        int vertexShader = MyGL20Renderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
+        int fragmentShader = MyGL20Renderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
+
+        mProgram = GLES20.glCreateProgram();             // create empty OpenGL ES Program
+        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
+        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
+        GLES20.glLinkProgram(mProgram);                  // creates OpenGL ES program executables
+    }
+    public void draw1() {
+        // Add program to OpenGL ES environment
+        GLES20.glUseProgram(mProgram);
+
+        // get handle to vertex shader's vPosition member
+        mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
+
+        // Enable a handle to the triangle vertices
+        GLES20.glEnableVertexAttribArray(mPositionHandle);
+
+        // Prepare the triangle coordinate data
+        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
+                                     GLES20.GL_FLOAT, false,
+                                     vertexStride, vertexBuffer);
+
+        // get handle to fragment shader's vColor member
+        mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
+
+        // Set color for drawing the triangle
+        GLES20.glUniform4fv(mColorHandle, 1, color, 0);
+
+        // Draw the triangle
+        GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
+
+        // Disable vertex array
+        GLES20.glDisableVertexAttribArray(mPositionHandle);
+    }
+}
+
Index: /issm/trunk/src/android/helloworld/Square/.classpath
===================================================================
--- /issm/trunk/src/android/helloworld/Square/.classpath	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/.classpath	(revision 13975)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="src" path="gen"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+	<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+	<classpathentry kind="output" path="bin/classes"/>
+</classpath>
Index: /issm/trunk/src/android/helloworld/Square/.project
===================================================================
--- /issm/trunk/src/android/helloworld/Square/.project	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/.project	(revision 13975)
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>Square</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>com.android.ide.eclipse.adt.ApkBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
Index: /issm/trunk/src/android/helloworld/Square/.settings/org.eclipse.jdt.core.prefs
===================================================================
--- /issm/trunk/src/android/helloworld/Square/.settings/org.eclipse.jdt.core.prefs	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/.settings/org.eclipse.jdt.core.prefs	(revision 13975)
@@ -0,0 +1,4 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.source=1.5
Index: /issm/trunk/src/android/helloworld/Square/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.square"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="10"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".Main"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/Square/bin/AndroidManifest.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/bin/AndroidManifest.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/bin/AndroidManifest.xml	(revision 13975)
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.square"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk
+        android:minSdkVersion="10"
+        android:targetSdkVersion="15" />
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name=".Main"
+            android:label="@string/title_activity_main" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
Index: /issm/trunk/src/android/helloworld/Square/bin/classes/com/example/square/SquareNumber.cpp
===================================================================
--- /issm/trunk/src/android/helloworld/Square/bin/classes/com/example/square/SquareNumber.cpp	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/bin/classes/com/example/square/SquareNumber.cpp	(revision 13975)
@@ -0,0 +1,7 @@
+#include libSquareNumber;
+
+JNIEXPORT jint JNICALL Java_org_edwards_1research_demo_jni_SquaredWrapper_squared
+  (JNIEnv * je, jclass jc, jint base)
+{
+        return (base*base);
+}
Index: /issm/trunk/src/android/helloworld/Square/bin/jarlist.cache
===================================================================
--- /issm/trunk/src/android/helloworld/Square/bin/jarlist.cache	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/bin/jarlist.cache	(revision 13975)
@@ -0,0 +1,3 @@
+# cache for current jar dependecy. DO NOT EDIT.
+# format is <lastModified> <length> <SHA-1> <path>
+# Encoding is UTF-8
Index: /issm/trunk/src/android/helloworld/Square/gen/com/example/square/BuildConfig.java
===================================================================
--- /issm/trunk/src/android/helloworld/Square/gen/com/example/square/BuildConfig.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/gen/com/example/square/BuildConfig.java	(revision 13975)
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.example.square;
+
+public final class BuildConfig {
+    public final static boolean DEBUG = true;
+}
Index: /issm/trunk/src/android/helloworld/Square/gen/com/example/square/R.java
===================================================================
--- /issm/trunk/src/android/helloworld/Square/gen/com/example/square/R.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/gen/com/example/square/R.java	(revision 13975)
@@ -0,0 +1,35 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package com.example.square;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_action_search=0x7f020000;
+        public static final int ic_launcher=0x7f020001;
+    }
+    public static final class id {
+        public static final int menu_settings=0x7f070000;
+    }
+    public static final class layout {
+        public static final int activity_main=0x7f030000;
+    }
+    public static final class menu {
+        public static final int activity_main=0x7f060000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040000;
+        public static final int hello_world=0x7f040001;
+        public static final int menu_settings=0x7f040002;
+        public static final int title_activity_main=0x7f040003;
+    }
+    public static final class style {
+        public static final int AppTheme=0x7f050000;
+    }
+}
Index: /issm/trunk/src/android/helloworld/Square/jni/Android.mk
===================================================================
--- /issm/trunk/src/android/helloworld/Square/jni/Android.mk	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/jni/Android.mk	(revision 13975)
@@ -0,0 +1,8 @@
+LOCAL_PATH := $(call my-dir)
+ 
+include $(CLEAR_VARS)
+ 
+LOCAL_MODULE    := squared
+LOCAL_SRC_FILES := SquaredNumber.cpp
+ 
+include $(BUILD_SHARED_LIBRARY)
Index: /issm/trunk/src/android/helloworld/Square/jni/square.h
===================================================================
--- /issm/trunk/src/android/helloworld/Square/jni/square.h	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/jni/square.h	(revision 13975)
@@ -0,0 +1,21 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+/* Header for class com_example_square_SquareNumber */
+
+#ifndef _Included_com_example_square_SquareNumber
+#define _Included_com_example_square_SquareNumber
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class:     com_example_square_SquareNumber
+ * Method:    squared
+ * Signature: (I)I
+ */
+JNIEXPORT jint JNICALL Java_com_example_square_SquareNumber_squared
+  (JNIEnv *, jclass, jint);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
Index: /issm/trunk/src/android/helloworld/Square/proguard-project.txt
===================================================================
--- /issm/trunk/src/android/helloworld/Square/proguard-project.txt	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/proguard-project.txt	(revision 13975)
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+#   http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+#   public *;
+#}
Index: /issm/trunk/src/android/helloworld/Square/project.properties
===================================================================
--- /issm/trunk/src/android/helloworld/Square/project.properties	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/project.properties	(revision 13975)
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
Index: /issm/trunk/src/android/helloworld/Square/res/layout/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/layout/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/layout/activity_main.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent" >
+
+</RelativeLayout>
Index: /issm/trunk/src/android/helloworld/Square/res/menu/activity_main.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/menu/activity_main.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/menu/activity_main.xml	(revision 13975)
@@ -0,0 +1,6 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:id="@+id/menu_settings"
+        android:title="@string/menu_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never" />
+</menu>
Index: /issm/trunk/src/android/helloworld/Square/res/values-v11/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/values-v11/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/values-v11/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/Square/res/values-v14/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/values-v14/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/values-v14/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/Square/res/values/strings.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/values/strings.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/values/strings.xml	(revision 13975)
@@ -0,0 +1,8 @@
+<resources>
+
+    <string name="app_name">Square</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="menu_settings">Settings</string>
+    <string name="title_activity_main">Main</string>
+
+</resources>
Index: /issm/trunk/src/android/helloworld/Square/res/values/styles.xml
===================================================================
--- /issm/trunk/src/android/helloworld/Square/res/values/styles.xml	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/res/values/styles.xml	(revision 13975)
@@ -0,0 +1,5 @@
+<resources>
+
+    <style name="AppTheme" parent="android:Theme.Light" />
+
+</resources>
Index: /issm/trunk/src/android/helloworld/Square/src/com/example/square/Main.java
===================================================================
--- /issm/trunk/src/android/helloworld/Square/src/com/example/square/Main.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/src/com/example/square/Main.java	(revision 13975)
@@ -0,0 +1,20 @@
+package com.example.square;
+
+import android.os.Bundle;
+import android.app.Activity;
+import android.view.Menu;
+
+public class Main extends Activity {
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.activity_main);
+    }
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        getMenuInflater().inflate(R.menu.activity_main, menu);
+        return true;
+    }
+}
Index: /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.cpp
===================================================================
--- /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.cpp	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.cpp	(revision 13975)
@@ -0,0 +1,7 @@
+#include libSquareNumber;
+
+JNIEXPORT jint JNICALL Java_org_edwards_1research_demo_jni_SquaredWrapper_squared
+  (JNIEnv * je, jclass jc, jint base)
+{
+        return (base*base);
+}
Index: /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.java
===================================================================
--- /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.java	(revision 13975)
+++ /issm/trunk/src/android/helloworld/Square/src/com/example/square/SquareNumber.java	(revision 13975)
@@ -0,0 +1,20 @@
+
+package com.example.square;
+
+
+public class SquareNumber {
+    // Declare native method (and make it public to expose it directly)
+    public static native int squared(int base);
+ 
+    // Provide additional functionality, that &quot;extends&quot; the native method
+    public static int to4(int base)
+    {
+        int sq = squared(base);
+        return squared(sq);
+    }
+ 
+    // Load library
+    static {
+        System.loadLibrary("libSquareNumber");
+    }
+}
Index: /issm/trunk/src/android/helloworld/code/Main.cpp
===================================================================
--- /issm/trunk/src/android/helloworld/code/Main.cpp	(revision 13975)
+++ /issm/trunk/src/android/helloworld/code/Main.cpp	(revision 13975)
@@ -0,0 +1,14 @@
+
+#include "com_lan_factorial_FacLib.h"
+#include "fac.h"
+
+//extern long fac(long n);
+
+JNIEXPORT jlong JNICALL Java_com_lan_factorial_FacLib_fac(JNIEnv *env, jclass clazz, jlong n)
+{
+
+	fac *f = new fac();
+	jlong result = (jlong) (f->factorial(n));
+	delete(f);
+	return result ;
+}
Index: /issm/trunk/src/android/helloworld/code/com_lan_factorial_FacLib.h
===================================================================
--- /issm/trunk/src/android/helloworld/code/com_lan_factorial_FacLib.h	(revision 13975)
+++ /issm/trunk/src/android/helloworld/code/com_lan_factorial_FacLib.h	(revision 13975)
@@ -0,0 +1,21 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+/* Header for class com_lan_factorial_FacLib */
+
+#ifndef _Included_com_lan_factorial_FacLib
+#define _Included_com_lan_factorial_FacLib
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class:     com_lan_factorial_FacLib
+ * Method:    fac
+ * Signature: (J)J
+ */
+JNIEXPORT jlong JNICALL Java_com_lan_factorial_FacLib_fac
+  (JNIEnv *, jclass, jlong);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
Index: /issm/trunk/src/android/helloworld/code/fac.cpp
===================================================================
--- /issm/trunk/src/android/helloworld/code/fac.cpp	(revision 13975)
+++ /issm/trunk/src/android/helloworld/code/fac.cpp	(revision 13975)
@@ -0,0 +1,14 @@
+#include "com_lan_factorial_FacLib.h"
+#include "fac.h"
+
+long fac::factorial(long n)
+{
+	long f = 1;
+	long i;
+	for(i = 1; i <= n; i++)
+	{
+		 f *= i;
+	}
+	return f;
+}
+
Index: /issm/trunk/src/android/helloworld/code/fac.h
===================================================================
--- /issm/trunk/src/android/helloworld/code/fac.h	(revision 13975)
+++ /issm/trunk/src/android/helloworld/code/fac.h	(revision 13975)
@@ -0,0 +1,5 @@
+class fac
+{
+	public:
+	long factorial(long n);
+};
Index: /issm/trunk/src/android/issm-android-inputfiles/test102.petsc
===================================================================
--- /issm/trunk/src/android/issm-android-inputfiles/test102.petsc	(revision 13975)
+++ /issm/trunk/src/android/issm-android-inputfiles/test102.petsc	(revision 13975)
@@ -0,0 +1,17 @@
+%Petsc options file: test102.petsc written from Matlab solver array
+
++NoneAnalysis
+-mat_type mpiaij
+-ksp_type preonly
+-pc_type lu
+-pc_factor_mat_solver_package mumps
+-mat_mumps_icntl_14 120
+-pc_factor_shift_positive_definite true
+
++DiagnosticVertAnalysis
+-mat_type mpiaij
+-ksp_type preonly
+-pc_type lu
+-pc_factor_mat_solver_package mumps
+-mat_mumps_icntl_14 120
+-pc_factor_shift_positive_definite true
Index: /issm/trunk/src/android/issm-android-inputfiles/test102.sh
===================================================================
--- /issm/trunk/src/android/issm-android-inputfiles/test102.sh	(revision 13975)
+++ /issm/trunk/src/android/issm-android-inputfiles/test102.sh	(revision 13975)
@@ -0,0 +1,2 @@
+#!/bin/sh
+/Users/larour/issm-uci/trunk-jpl/bin/issm.exe DiagnosticSolution /Users/larour/issm-uci/trunk-jpl/src/android/test102 test102 
Index: /issm/trunk/src/c/Container/Constraints.cpp
===================================================================
--- /issm/trunk/src/c/Container/Constraints.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Constraints.cpp	(revision 13975)
@@ -49,10 +49,9 @@
 	/*figure out total number of constraints combining all the cpus (no clones here)*/
 	#ifdef _HAVE_MPI_
-		MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-		MPI_Bcast(&numberofconstraints,1,MPI_INT,0,MPI_COMM_WORLD);
+		MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+		MPI_Bcast(&numberofconstraints,1,MPI_INT,0,IssmComm::GetComm());
 	#else
 		numberofconstraints=localconstraints;
 	#endif
-	
 
 	return numberofconstraints;
Index: /issm/trunk/src/c/Container/Constraints.h
===================================================================
--- /issm/trunk/src/c/Container/Constraints.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Constraints.h	(revision 13975)
@@ -16,20 +16,16 @@
 class Inputs;
 
-
 class Constraints: public DataSet{
 
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Constraints();
 		~Constraints();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		int   NumberOfConstraints(void);
-		/*}}}*/
 
 };
 
-
 #endif //ifndef _CONSTRAINTS_H_
-
Index: /issm/trunk/src/c/Container/DataSet.cpp
===================================================================
--- /issm/trunk/src/c/Container/DataSet.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/DataSet.cpp	(revision 13975)
@@ -30,5 +30,5 @@
 /*FUNCTION DataSet::DataSet(){{{*/
 DataSet::DataSet(){
-	
+
 	sorted=0;
 	sorted_ids=NULL;
@@ -40,5 +40,5 @@
 DataSet::DataSet(int dataset_enum){
 	enum_type=dataset_enum;
-	
+
 	sorted=0;
 	sorted_ids=NULL;
@@ -50,9 +50,8 @@
 DataSet*   DataSet::Copy(void){
 
-	DataSet* copy=NULL;
 	vector<Object*>::iterator object;
 	Object* object_copy=NULL;
 
-	copy=new DataSet(enum_type);
+	DataSet* copy=new DataSet(enum_type);
 
 	copy->sorted=sorted;
@@ -130,5 +129,4 @@
 void DataSet::DeepEcho(){
 
-
 	vector<Object*>::iterator object;
 
@@ -191,5 +189,4 @@
 	int id_offset;
 	int offset;
-	int i;
 
 	_assert_(this);
@@ -216,6 +213,4 @@
 	/*vector of objects is already sorted, just allocate the sorted ids and their
 	 * offsets:*/
-	int i;
-
 	if(objects.size()){
 
@@ -229,5 +224,5 @@
 
 		/*Build id_offsets and sorted_ids*/
-		for(i=0;i<objects.size();i++){
+		for(int i=0;i<objects.size();i++){
 			id_offsets[i]=i;
 			sorted_ids[i]=objects[i]->Id();
Index: /issm/trunk/src/c/Container/DataSet.h
===================================================================
--- /issm/trunk/src/c/Container/DataSet.h	(revision 13974)
+++ /issm/trunk/src/c/Container/DataSet.h	(revision 13975)
@@ -23,13 +23,13 @@
 
 class DataSet{
-	
+
 	public: 
-		
+
 		/*internals: */
 		std::vector<Object*> objects;
-		
+
 		/*type of dataset: */
 		int             enum_type;
-		
+
 		/*sorting: */
 		int             sorted;
@@ -38,27 +38,26 @@
 		int*            id_offsets;
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		DataSet();
 		DataSet(int enum_type);
 		~DataSet();
-		/*}}}*/
-		/*management: {{{*/
-		int   GetEnum();
-		int   GetEnum(int offset);
-		void  Echo();
-		void  DeepEcho();
-		int   AddObject(Object* object);
-		int   DeleteObject(int id);
-		int   Size();
-		void  clear();
-		Object* GetObjectByOffset(int offset);
-		Object* GetObjectById(int* poffset,int eid);
-		void  Presort();
-		void  SetSorting(int* in_sorted_ids,int* in_id_offsets);
-		void  Sort();
-		DataSet* Copy(void);
-		int   DeleteObject(Object* object);
-		Results* SpawnTriaResults(int* indices);
-		/*}}}*/
+
+		/*management*/
+		int      GetEnum();
+		int      GetEnum(int offset);
+		void     Echo();
+		void     DeepEcho();
+		int      AddObject(Object *object);
+		int      DeleteObject(int id);
+		int      Size();
+		void     clear();
+		Object  *GetObjectByOffset(int  offset);
+		Object  *GetObjectById(int *poffset,int eid);
+		void     Presort();
+		void     SetSorting(int *in_sorted_ids,int*in_id_offsets);
+		void     Sort();
+		DataSet *Copy(void);
+		int      DeleteObject(Object *object);
+		Results *SpawnTriaResults(int *indices);
 
 };
Index: /issm/trunk/src/c/Container/Elements.cpp
===================================================================
--- /issm/trunk/src/c/Container/Elements.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Elements.cpp	(revision 13975)
@@ -46,5 +46,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		element=(Element*)(*object);
+		element=dynamic_cast<Element*>((*object));
 		element->Configure(elements,loads,nodes,materials,parameters);
 
@@ -58,5 +58,5 @@
 	//Process results to be output in the correct units
 	for(int i=0;i<this->Size();i++){
-		Element* element=(Element*)this->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
 		element->ProcessResultsUnits();
 	}
@@ -65,7 +65,7 @@
 /*FUNCTION Elements::DeleteResults{{{*/
 void Elements::DeleteResults(void){
-	
+
 	for (int i=0;i<this->Size();i++){
-		Element* element=(Element*)this->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
 		element->DeleteResults();
 	}
@@ -108,5 +108,5 @@
 	 * We will use the Patch object, which will store all of the information needed, and will be able 
 	 * to output itself to disk on its own. See object/Patch.h for format of this object.*/
-	
+
 	/*First, determine maximum number of vertices, nodes, and number of results: */
 	numrows=0;
@@ -116,5 +116,5 @@
 	for(i=0;i<this->Size();i++){
 
-		Element* element=(Element*)this->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
 		element->PatchSize(&element_numrows,&element_numvertices,&element_numnodes);
 
@@ -126,10 +126,10 @@
 	/*Synchronize across cluster, so as to not end up with different sizes for each patch on each cpu: */
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&max_numvertices,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&max_numvertices,1,MPI_INT,0,IssmComm::GetComm());
 	numvertices=max_numvertices;
 
-	MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&max_numnodes,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&max_numnodes,1,MPI_INT,0,IssmComm::GetComm());
 	numnodes=max_numnodes;
 	#endif
@@ -141,5 +141,5 @@
 	count=0;
 	for(i=0;i<this->Size();i++){
-		Element* element=(Element*)this->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
 		element->PatchFill(&count,patch);
 	}
@@ -156,5 +156,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		element=(Element*)(*object);
+		element=dynamic_cast<Element*>((*object));
 		element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
 
@@ -166,22 +166,24 @@
 void Elements::ToResults(Results* results,Parameters* parameters){
 
-	int i;
-	
-	extern int my_rank;
-	extern int num_procs;
-
-	Patch  *patch        = NULL;
-	int    *resultsenums = NULL;
-	int    *resultssizes  = NULL;
-	int    *resultssteps  = NULL;
-	IssmDouble *resultstimes = NULL;
-	IssmDouble *vector_serial= NULL;
-	Vector<IssmDouble>*     vector       = NULL;
-	bool   io_gather;
-	bool   results_as_patches;
-	int    numberofvertices,numberofelements;
-	int    numberofresults,vectorsize;
-	int    rank;
-	int    minrank;
+	int my_rank;
+	int num_procs;
+
+	Patch               *patch              = NULL;
+	int                 *resultsenums       = NULL;
+	int                 *resultssizes       = NULL;
+	int                 *resultssteps       = NULL;
+	IssmDouble          *resultstimes       = NULL;
+	IssmDouble          *vector_serial      = NULL;
+	Vector<IssmDouble> *vector = NULL;
+	bool                io_gather;
+	bool                results_as_patches;
+	int                 numberofvertices     ,numberofelements;
+	int                 numberofresults      ,vectorsize;
+	int                 rank;
+	int                 minrank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
 
 	/*Recover parameters: */
@@ -198,5 +200,5 @@
 		if(this->Size()) rank=my_rank;
 		else rank=num_procs;
-		MPI_Allreduce (&rank,&minrank,1,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
+		MPI_Allreduce (&rank,&minrank,1,MPI_INT,MPI_MIN,IssmComm::GetComm());
 		#else
 		minrank=my_rank;
@@ -206,9 +208,9 @@
 		if(my_rank==minrank){
 			if(this->Size()==0) _error_("Cannot write results because there is no element??");
-			Element* element=(Element*)this->GetObjectByOffset(0);
+			Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(0));
 			element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
 		}
 		#ifdef _HAVE_MPI_
-		MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,MPI_COMM_WORLD);
+		MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,IssmComm::GetComm());
 		#endif
 
@@ -222,8 +224,8 @@
 			resultssteps=xNew<int>(numberofresults);
 		}
-		MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
-		MPI_Bcast(resultssizes,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
-		MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,minrank,MPI_COMM_WORLD);
-		MPI_Bcast(resultssteps,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
+		MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
+		MPI_Bcast(resultssizes,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
+		MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,minrank,IssmComm::GetComm());
+		MPI_Bcast(resultssteps,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
 		#endif
 
@@ -238,5 +240,5 @@
 
 			for(int j=0;j<this->Size();j++){
-				Element* element=(Element*)this->GetObjectByOffset(j);
+				Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(j));
 				element->GetVectorFromResults(vector,i,resultsenums[i],resultssizes[i]);
 			}
@@ -292,13 +294,37 @@
 }
 /*}}}*/
+/*FUNCTION Elements::MaxNumNodes{{{*/
+int Elements::MaxNumNodes(void){
+
+	int max=0;
+	int allmax;
+	int numnodes=0;
+
+	/*Now go through all elements, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
+		numnodes=element->GetNumberOfNodes();
+		if(numnodes>max)max=numnodes;
+	}
+
+	/*Grab max of all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+	#endif
+
+	return max;
+}
+/*}}}*/
 /*FUNCTION Elements::NumberOfElements{{{*/
 int Elements::NumberOfElements(void){
 
-	int local_nelem=0;
+	int local_nelem;
 	int numberofelements;
 
 	local_nelem=this->Size();
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
 	#else
 	numberofelements=local_nelem;
@@ -312,5 +338,5 @@
 
 	for(int i=0;i<this->Size();i++){
-		Element* element=(Element*)this->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
 		element->InputDuplicate(input_enum,output_enum);
 	}
Index: /issm/trunk/src/c/Container/Elements.h
===================================================================
--- /issm/trunk/src/c/Container/Elements.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Elements.h	(revision 13975)
@@ -20,18 +20,18 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Elements();
 		~Elements();
-		/*}}}*/
-		/*numerics: {{{*/
-		void Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		void DeleteResults(void);
-		void ProcessResultsUnits(void);
-		void SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		void ToResults(Results* results,Parameters* parameters);
+
+		/*numerics*/
+		void   Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void   DeleteResults(void);
+		int    MaxNumNodes(void);
+		void   ProcessResultsUnits(void);
+		void   SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		void   ToResults(Results* results,Parameters* parameters);
 		Patch* ResultsToPatch(void);
-		int   NumberOfElements(void);
-		void InputDuplicate(int input_enum,int output_enum);
-		/*}}}*/
+		int    NumberOfElements(void);
+		void   InputDuplicate(int input_enum,int output_enum);
 
 };
Index: /issm/trunk/src/c/Container/Inputs.cpp
===================================================================
--- /issm/trunk/src/c/Container/Inputs.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Inputs.cpp	(revision 13975)
@@ -47,5 +47,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -75,5 +75,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -103,5 +103,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object); 
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -131,5 +131,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 		if (input->InstanceEnum()==enum_type){
 			found=true;
@@ -163,5 +163,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 
 		if (input->InstanceEnum()==in_input->InstanceEnum()){
@@ -185,5 +185,5 @@
 	/*Delete existing input of newenumtype if it exists*/
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 
 		if (input->InstanceEnum()==newenumtype){
@@ -196,5 +196,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 
 		if (input->InstanceEnum()==oldenumtype){
@@ -207,8 +207,7 @@
 /*FUNCTION Inputs::ConstrainMin{{{*/
 void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){
-	   
-	Input* constrain_input=NULL; 
+
 	/*Find x and y inputs: */
-	constrain_input=(Input*)this->GetInput(constrain_enum);
+	Input* constrain_input=dynamic_cast<Input*>(this->GetInput(constrain_enum));
 
 	/*some checks: */
@@ -226,5 +225,5 @@
 
 	/*Get input*/
-	Input* input=(Input*)this->GetInput(enumtype);
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -247,5 +246,5 @@
 
 	/*Get input*/
-	Input* input=(Input*)this->GetInput(enumtype);
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -268,5 +267,5 @@
 
 	/*Get input*/
-	Input* input=(Input*)this->GetInput(enumtype);
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -289,5 +288,5 @@
 
 	/*Get input*/
-	Input* input=(Input*)this->GetInput(enumtype);
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -310,5 +309,5 @@
 
 	/*Get input*/
-	Input* input=(Input*)this->GetInput(enumtype);
+	Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
 
 	/*Apply ContrainMin: */
@@ -332,5 +331,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 
 		if (input->InstanceEnum()==enum_name){
@@ -349,5 +348,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object); 
+		input=dynamic_cast<Input*>(*object);
 
 		if (input->InstanceEnum()==enum_type){
@@ -364,11 +363,8 @@
 void  Inputs::DuplicateInput(int original_enum,int new_enum){
 
-	Input* original=NULL;
-	Input* copy=NULL;
-
 	/*Make a copy of the original input: */
-	original=(Input*)this->GetInput(original_enum);
+	Input* original=dynamic_cast<Input*>(this->GetInput(original_enum));
 	if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum)); 
-	copy=(Input*)original->copy();
+	Input* copy=dynamic_cast<Input*>(original->copy());
 
 	/*Change copy enum to reinitialized_enum: */
@@ -376,5 +372,5 @@
 
 	/*Add copy into inputs, it will wipe off the one already there: */
-	this->AddInput((Input*)copy);
+	this->AddInput(dynamic_cast<Input*>(copy));
 }
 /*}}}*/
@@ -394,5 +390,5 @@
 
 		/*Create new input*/
-		inputin=(Input*)(*object); 
+		inputin=dynamic_cast<Input*>(*object);
 		inputout=inputin->SpawnTriaInput(indices);
 
@@ -407,11 +403,8 @@
 /*FUNCTION Inputs::AXPY{{{*/
 void  Inputs::AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum){
-	   
-	Input* xinput=NULL;
-	Input* yinput=NULL;
 
 	/*Find x and y inputs: */
-	xinput=(Input*)this->GetInput(MeshXEnum);
-	yinput=(Input*)this->GetInput(MeshYEnum);
+	Input* xinput=dynamic_cast<Input*>(this->GetInput(MeshXEnum));
+	Input* yinput=dynamic_cast<Input*>(this->GetInput(MeshYEnum));
 
 	/*some checks: */
@@ -431,5 +424,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		input=(Input*)(*object);
+		input=dynamic_cast<Input*>(*object);
 		input->Configure(parameters);
 
Index: /issm/trunk/src/c/Container/Inputs.h
===================================================================
--- /issm/trunk/src/c/Container/Inputs.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Inputs.h	(revision 13975)
@@ -23,18 +23,17 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Inputs();
 		~Inputs();
 
-		/*}}}*/
-		/*numerics: {{{*/
-		int     AddInput(Input* in_input);
-		void    ChangeEnum(int enumtype,int new_enumtype);
-		void    ConstrainMin(int constrain_enum, IssmDouble minimum);
-		int     DeleteInput(int enum_type);
-		void    DuplicateInput(int original_enum,int new_enum);
-		Input*  GetInput(int enum_name);
-		Inputs* SpawnTriaInputs(int* indices);
-		void    AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
+		/*numerics*/
+		int        AddInput(Input* in_input);
+		void       ChangeEnum(int enumtype,int new_enumtype);
+		void       ConstrainMin(int constrain_enum, IssmDouble minimum);
+		int        DeleteInput(int enum_type);
+		void       DuplicateInput(int original_enum,int new_enum);
+		Input*     GetInput(int enum_name);
+		Inputs*    SpawnTriaInputs(int* indices);
+		void       AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
 		IssmDouble  InfinityNorm(int enumtype);
 		IssmDouble  Max(int enumtype);
@@ -42,12 +41,9 @@
 		IssmDouble  Min(int enumtype);
 		IssmDouble  MinAbs(int enumtype);
-		
 		void GetInputAverage(IssmDouble* pvalue, int enum_type);
 		void GetInputValue(bool* pvalue,int enum_type);
 		void GetInputValue(int* pvalue,int enum_type);
 		void GetInputValue(IssmDouble* pvalue,int enum_type);
-
 		void Configure(Parameters* parameters);
-		/*}}}*/
 
 };
Index: /issm/trunk/src/c/Container/Loads.cpp
===================================================================
--- /issm/trunk/src/c/Container/Loads.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Loads.cpp	(revision 13975)
@@ -46,5 +46,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		load=(Load*)(*object);
+		load=dynamic_cast<Load*>(*object);
 		load->Configure(elements,loads,nodes,vertices,materials,parameters);
 
@@ -53,9 +53,62 @@
 }
 /*}}}*/
-/*FUNCTION Loads::NumberOfLoads{{{*/
+/*FUNCTION Loads::IsPenalty{{{*/
+bool Loads::IsPenalty(int analysis_type){
+
+	int ispenalty=0;
+	int allispenalty=0;
+
+	/*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		if (load->InAnalysis(analysis_type)){
+			if(load->IsPenalty()) ispenalty++;
+		}
+	}
+
+	/*Grab sum of all cpus: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	ispenalty=allispenalty;
+#endif
+
+	if(ispenalty)
+	 return true;
+	else
+	 return false;
+}
+/*}}}*/
+/*FUNCTION Loads::MaxNumNodes{{{*/
+int Loads::MaxNumNodes(int analysis_type){
+
+	int max=0;
+	int allmax;
+	int numnodes=0;
+
+	/*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+		if (load->InAnalysis(analysis_type)){
+			numnodes=load->GetNumberOfNodes();
+			if(numnodes>max)max=numnodes;
+		}
+	}
+
+	/*Grab max of all cpus: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	max=allmax;
+#endif
+
+	return max;
+}
+/*}}}*/
+/*FUNCTION Loads::NumberOfLoads(){{{*/
 int Loads::NumberOfLoads(void){
 
-	int localloads=0;
-	int numberofloads=0;
+	int localloads;
+	int numberofloads;
 
 	/*Get number of local loads*/
@@ -64,12 +117,60 @@
 	/*figure out total number of loads combining all the cpus (no clones here)*/
 	#ifdef _HAVE_MPI_
-	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&numberofloads,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
 	#else
 	numberofloads=localloads;
 	#endif
 
+	return numberofloads;
+}
+/*}}}*/
+/*FUNCTION Loads::NumberOfLoads(int analysis){{{*/
+int Loads::NumberOfLoads(int analysis_type){
+
+	int localloads = 0;
+	int numberofloads;
+
+	/*Get number of local loads*/
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+
+		/*Check that this load corresponds to our analysis currently being carried out: */
+		if (load->InAnalysis(analysis_type)) localloads++;
+	}
+
+	/*figure out total number of loads combining all the cpus (no clones here)*/
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
+#else
+	numberofloads=localloads;
+#endif
 
 	return numberofloads;
+}
+/*}}}*/
+/*FUNCTION Loads::Size(){{{*/
+int Loads::Size(void){
+
+	return this->DataSet::Size();
+}
+/*}}}*/
+/*FUNCTION Loads::Size(int analysis){{{*/
+int Loads::Size(int analysis_type){
+
+	int localloads = 0;
+
+	/*Get number of local loads*/
+	for(int i=0;i<this->Size();i++){
+
+		Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
+
+		/*Check that this load corresponds to our analysis currently being carried out: */
+		if (load->InAnalysis(analysis_type)) localloads++;
+	}
+
+	return localloads;
 }
 /*}}}*/
@@ -82,5 +183,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		load=(Load*)(*object);
+		load=dynamic_cast<Load*>(*object);
 		load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
 
Index: /issm/trunk/src/c/Container/Loads.h
===================================================================
--- /issm/trunk/src/c/Container/Loads.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Loads.h	(revision 13975)
@@ -20,13 +20,17 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Loads();
 		~Loads();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
+		bool  IsPenalty(int analysis);
+		int   MaxNumNodes(int analysis);
 		int   NumberOfLoads(void);
+		int   NumberOfLoads(int analysis);
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		/*}}}*/
+		int   Size(int analysis);
+		int   Size(void);
 
 };
Index: /issm/trunk/src/c/Container/Materials.cpp
===================================================================
--- /issm/trunk/src/c/Container/Materials.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Materials.cpp	(revision 13975)
@@ -46,5 +46,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		material=(Material*)(*object);
+		material=dynamic_cast<Material*>(*object);
 		material->Configure(elements);
 
Index: /issm/trunk/src/c/Container/Materials.h
===================================================================
--- /issm/trunk/src/c/Container/Materials.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Materials.h	(revision 13975)
@@ -19,11 +19,10 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Materials();
 		~Materials();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		/*}}}*/
 
 };
Index: /issm/trunk/src/c/Container/Nodes.cpp
===================================================================
--- /issm/trunk/src/c/Container/Nodes.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Nodes.cpp	(revision 13975)
@@ -46,5 +46,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		node=(Node*)(*object);
+		node=dynamic_cast<Node*>(*object);
 		node->Configure(nodes,vertices);
 
@@ -55,7 +55,4 @@
 /*FUNCTION Nodes::DistributeDofs{{{*/
 void  Nodes::DistributeDofs(int analysis_type,int setenum){
-
-	extern int num_procs;
-	extern int my_rank;
 
 	int  i;
@@ -67,4 +64,8 @@
 	int  numnodes=0;
 
+	/*recover my_rank:*/
+	int my_rank   = IssmComm::GetRank();
+	int num_procs = IssmComm::GetSize();
+
 	/*some check: */
 	_assert_(setenum==GsetEnum || setenum==FsetEnum || setenum==SsetEnum);
@@ -72,5 +73,5 @@
 	/*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
 	for (i=0;i<this->Size();i++){
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -86,6 +87,6 @@
 	alldofcount=xNew<int>(num_procs);
 	#ifdef _HAVE_MPI_
-	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
-	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,IssmComm::GetComm());
+	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,IssmComm::GetComm());
 	#else
 	alldofcount[0]=dofcount;
@@ -94,12 +95,10 @@
 	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
 	dofcount=0;
-	if(my_rank!=0){
-		for(i=0;i<my_rank;i++){
-			dofcount+=alldofcount[i];
-		}
+	for(i=0;i<my_rank;i++){
+		dofcount+=alldofcount[i];
 	}
 	for (i=0;i<this->Size();i++){
 		/*Check that this node corresponds to our analysis currently being carried out: */
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->OffsetDofs(dofcount,setenum);
@@ -118,5 +117,5 @@
 
 	for (i=0;i<this->Size();i++){
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->ShowTrueDofs(truedofs,maxdofspernode,setenum);//give maxdofspernode, column size, so that nodes can index into truedofs
@@ -125,5 +124,5 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+	MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,IssmComm::GetComm());
 	#else
 	for(i=0;i<numnodes*maxdofspernode;i++)alltruedofs[i]=truedofs[i];
@@ -132,5 +131,5 @@
 	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
 	for (i=0;i<this->Size();i++){
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 		if (node->InAnalysis(analysis_type)){
 			node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
@@ -148,9 +147,9 @@
 
 	int i;
-	extern int num_procs;
-
-	int* ranks=NULL;
-	int* minranks=NULL;
-	int  numnodes;
+	int num_procs;
+	int numnodes;
+
+	/*recover num_procs: */
+	num_procs=IssmComm::GetSize();
 
 	/*Figure out number of nodes for this analysis: */
@@ -158,7 +157,6 @@
 
 	/*Allocate ranks: */
-	ranks=xNew<int>(numnodes);
-	minranks=xNew<int>(numnodes);
-
+	int* ranks    = xNew<int>(numnodes);
+	int* minranks = xNew<int>(numnodes);
 	for(i=0;i<numnodes;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
 
@@ -171,5 +169,5 @@
 	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
+	MPI_Allreduce((void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,IssmComm::GetComm());
 	#else
 	for(i=0;i<numnodes;i++)minranks[i]=ranks[i];
@@ -179,5 +177,5 @@
 	for(i=0;i<this->Size();i++){
 
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -199,12 +197,12 @@
 
 	int i;
-	int   max=0;
-	int   allmax;
-	int   numdofs=0;
+	int max=0;
+	int allmax;
+	int numdofs=0;
 
 	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
 	for(i=0;i<this->Size();i++){
 
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -212,5 +210,5 @@
 
 			numdofs=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
-			if (numdofs>max)max=numdofs;
+			if(numdofs>max)max=numdofs;
 		}
 	}
@@ -218,5 +216,5 @@
 	/*Grab max of all cpus: */
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+	MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
 	max=allmax;
 	#endif
@@ -228,13 +226,27 @@
 int   Nodes::NumberOfDofs(int analysis_type,int setenum){
 
-	int i;
-	
+	int   allnumdofs;
+
+	/*Get number of dofs on current cpu (excluding clones)*/
+	int numdofs=this->NumberOfDofsLocal(analysis_type,setenum);
+
+	/*Gather from all cpus: */
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	#else
+	allnumdofs=numdofs;
+	#endif
+	return allnumdofs;
+}
+/*}}}*/
+/*FUNCTION Nodes::NumberOfDofsLocal{{{*/
+int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){
+
 	int   numdofs=0;
-	int   allnumdofs;
 
 	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
-	for(i=0;i<this->Size();i++){
-
-		Node* node=(Node*)this->GetObjectByOffset(i);
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -243,18 +255,10 @@
 			/*Ok, this object is a node, ask it to plug values into partition: */
 			if (!node->IsClone()){
-
 				numdofs+=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
-
 			}
 		}
 	}
 
-	/*Gather from all cpus: */
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
-	#else
-	allnumdofs=numdofs;
-	#endif
-	return allnumdofs;
+	return numdofs;
 }
 /*}}}*/
@@ -264,12 +268,10 @@
 	/*Careful! only use once all clones have been setup for all nodes!: */
 
-	int i;
-	
-	int   numnodes=0;
-	int   allnumnodes=0;
+	int numnodes=0;
+	int allnumnodes=0;
 
 	/*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
-	for(i=0;i<this->Size();i++){
-		Node* node=(Node*)this->GetObjectByOffset(i);
+	for(int i=0;i<this->Size();i++){
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Ok, this object is a node, ask it to plug values into partition: */
@@ -279,5 +281,5 @@
 	/*Gather from all cpus: */
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
 	#else
 	allnumnodes=numnodes;
@@ -298,5 +300,5 @@
 	for(i=0;i<this->Size();i++){
 
-		Node* node=(Node*)this->GetObjectByOffset(i);
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
 
 		/*Check that this node corresponds to our analysis currently being carried out: */
@@ -309,19 +311,14 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&node_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_max_sid,1,MPI_INT,0,IssmComm::GetComm());
 	max_sid=node_max_sid;
 	#endif
 
-	if(max_sid==1){
-		return 0;
-	}
-	else{
-		/*sid starts at 0*/
-		max_sid++;
-	
-		/*return*/
-		return max_sid;
-	}
+	/*sid starts at 0*/
+	max_sid++;
+
+	/*return*/
+	return max_sid;
 }
 /*}}}*/
@@ -329,25 +326,22 @@
 void   Nodes::Ranks(int* ranks,int analysis_type){
 
+	int my_rank;
+	int sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*Go through nodes, and for each object, report it cpu: */
-
-	int i;
-	int rank;
-	int sid;
-	
-	for(i=0;i<this->Size();i++){
-
-		Node* node=(Node*)this->GetObjectByOffset(i);
-
-		/*Check that this node corresponds to our analysis currently being carried out: */
-		if (node->InAnalysis(analysis_type)){
-
-			rank=node->MyRank();
+	for(int i=0;i<this->Size();i++){
+
+		Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
+
+		/*Check that this node corresponds to our analysis currently being carried out: */
+		if (node->InAnalysis(analysis_type)){
+			/*Plug rank into ranks, according to sid: */
 			sid=node->Sid();
-
-			/*Plug rank into ranks, according to id: */
-			ranks[sid]=rank; 
-		}
-	}
-	return;
+			ranks[sid]=my_rank; 
+		}
+	}
 }
 /*}}}*/
@@ -358,11 +352,10 @@
 	Node* node=NULL;
 
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		node=(Node*)(*object);
+	for (object=objects.begin() ; object < objects.end(); object++ ){
+
+		node=dynamic_cast<Node*>(*object);
 		node->SetCurrentConfiguration(nodes,vertices);
 
 	}
-
-}
-/*}}}*/
+}
+/*}}}*/
Index: /issm/trunk/src/c/Container/Nodes.h
===================================================================
--- /issm/trunk/src/c/Container/Nodes.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Nodes.h	(revision 13975)
@@ -13,9 +13,9 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Nodes();
 		~Nodes();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
 		void  DistributeDofs(int analysis_type,int SETENUM);
@@ -23,9 +23,9 @@
 		int   MaxNumDofs(int analysis_type,int setenum);
 		int   NumberOfDofs(int analysis_type,int setenum);
+		int   NumberOfDofsLocal(int analysis_type,int setenum);
 		int   NumberOfNodes(int analysis_type);
 		int   NumberOfNodes(void);
 		void  Ranks(int* ranks,int analysis_type);
 		void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
-		/*}}}*/
 
 };
Index: /issm/trunk/src/c/Container/Observations.cpp
===================================================================
--- /issm/trunk/src/c/Container/Observations.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Observations.cpp	(revision 13975)
@@ -40,5 +40,5 @@
 
 	/*Intermediaries*/
-	int          i,j,maxdepth,level,counter,index;
+	int          i,maxdepth,level,counter,index;
 	int          xi,yi;
 	IssmPDouble  xmin,xmax,ymin,ymax;
@@ -88,5 +88,5 @@
 		this->quadtree->ClosestObs(&index,x[i],y[i]);
 		if(index>=0){
-			observation=(Observation*)this->GetObjectByOffset(index);
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
 			if(pow(observation->x-x[i],2)+pow(observation->y-y[i],2) < minspacing) continue;
 		}
@@ -121,5 +121,4 @@
 
 	/*Output and Intermediaries*/
-	bool         stop;
 	int          nobs,i,index;
 	IssmPDouble  h2,hmin2,radius2;
@@ -136,5 +135,5 @@
 	this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,radius);
 	for (i=0;i<nobs;i++){
-		observation=(Observation*)this->GetObjectByOffset(indices[i]);
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
 		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
 
@@ -158,5 +157,5 @@
 	}
 	else{
-		observation=(Observation*)this->GetObjectByOffset(indices[index]);
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[index]));
 		*px=observation->x;
 		*py=observation->y;
@@ -195,5 +194,5 @@
 	nobs = 0;
 	for (i=0;i<tempnobs;i++){
-		observation=(Observation*)this->GetObjectByOffset(tempindices[i]);
+		observation=dynamic_cast<Observation*>(this->GetObjectByOffset(tempindices[i]));
 		h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
 
@@ -237,5 +236,5 @@
 		/*Loop over all observations and fill in x, y and obs*/
 		for (i=0;i<nobs;i++){
-			observation=(Observation*)this->GetObjectByOffset(indices[i]);
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
 			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
 		}
@@ -266,5 +265,5 @@
 		obs = xNew<IssmPDouble>(nobs);
 		for(int i=0;i<this->Size();i++){
-			observation=(Observation*)this->GetObjectByOffset(i);
+			observation=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
 			observation->WriteXYObs(&x[i],&y[i],&obs[i]);
 		}
@@ -451,8 +450,8 @@
 
 	for(i=0;i<this->Size();i++){
-		observation1=(Observation*)this->GetObjectByOffset(i);
+		observation1=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
 
 		for(j=i+1;j<this->Size();j++){
-			observation2=(Observation*)this->GetObjectByOffset(j);
+			observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
 
 			distance=sqrt(pow(observation1->x - observation2->x,2.) + pow(observation1->y - observation2->y,2.));
Index: /issm/trunk/src/c/Container/Observations.h
===================================================================
--- /issm/trunk/src/c/Container/Observations.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Observations.h	(revision 13975)
@@ -37,3 +37,2 @@
 };
 #endif //ifndef _OBSERVATIONS_H_
-
Index: /issm/trunk/src/c/Container/Options.cpp
===================================================================
--- /issm/trunk/src/c/Container/Options.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Options.cpp	(revision 13975)
@@ -42,5 +42,5 @@
 
 	char* name=NULL;
-	
+
 	vector<Object*>::iterator object;
 	Option* option=NULL;
@@ -60,5 +60,5 @@
 	for(object=objects.begin();object<objects.end();object++){
 
-		option=(Option*)(*object); 
+		option=dynamic_cast<Option*>(*object);
 		if (!strcmp(option->Name(),name)){
 			_error_("Options \"" << name << "\" found multiple times");
@@ -82,5 +82,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		option=(Option*)(*object); 
+		option=dynamic_cast<Option*>(*object);
 		if (!strncmp(name,option->Name(),strlen(option->Name()))){
 
Index: /issm/trunk/src/c/Container/Options.h
===================================================================
--- /issm/trunk/src/c/Container/Options.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Options.h	(revision 13975)
@@ -22,13 +22,9 @@
 		int  AddOption(Option* in_oobject);
 		Option* GetOption(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);
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -44,9 +40,6 @@
 		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);
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -63,9 +56,6 @@
 		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);
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -80,9 +70,6 @@
 		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);
+			GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
 
 			/*If the pointer is not NULL, the option has been found*/
@@ -103,9 +90,6 @@
 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);
+	GenericOption<char*>* genericoption=dynamic_cast<GenericOption<char*>*>(GetOption(name));
 
 	/*If the pointer is not NULL, the option has been found*/
@@ -115,9 +99,6 @@
 	else{
 		/*Make a copy*/
-		char* outstring=NULL;
-		int   stringsize;
-
-		stringsize=strlen(default_value)+1;
-		outstring=xNew<char>(stringsize);
+		int   stringsize=strlen(default_value)+1;
+		char* 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 13974)
+++ /issm/trunk/src/c/Container/Parameters.cpp	(revision 13975)
@@ -45,5 +45,5 @@
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type) return true;
 	}
@@ -53,11 +53,11 @@
 /*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{*/
 void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pbool);
@@ -70,11 +70,11 @@
 /*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{*/
 void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pinteger);
@@ -87,11 +87,11 @@
 /*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type){{{*/
 void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pscalar);
@@ -110,5 +110,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pscalar,time);
@@ -121,11 +121,11 @@
 /*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{*/
 void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pstring);
@@ -139,11 +139,11 @@
 /*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{*/
 void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pstringarray,pM);
@@ -163,5 +163,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pintarray,pM);
@@ -181,5 +181,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pintarray,pM,pN);
@@ -199,5 +199,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pIssmDoublearray,pM);
@@ -217,5 +217,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pIssmDoublearray,pM,pN);
@@ -229,11 +229,11 @@
 /*FUNCTION Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{*/
 void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
@@ -246,11 +246,11 @@
 /*FUNCTION Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){{{*/
 void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pvec);
@@ -264,11 +264,11 @@
 /*FUNCTION Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){{{*/
 void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);
-	
-	vector<Object*>::iterator object;
-	Param* param=NULL;
-
-	for ( object=objects.begin() ; object < objects.end(); object++ ){
-
-		param=(Param*)(*object);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pmat);
@@ -288,7 +288,25 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			param->GetParameterValue(pfid);
+			return;
+		}
+	}
+	_error_("could not find parameter " << EnumToStringx(enum_type));
+}
+/*}}}*/
+/*FUNCTION Parameters::FindParam(DataSet** pdataset,int enum_type){{{*/
+void Parameters::FindParam(DataSet** pdataset,int enum_type){ 
+	_assert_(this);
+
+	vector<Object*>::iterator object;
+	Param* param=NULL;
+
+	for ( object=objects.begin() ; object < objects.end(); object++ ){
+
+		param=dynamic_cast<Param*>(*object);
+		if(param->InstanceEnum()==enum_type){
+			param->GetParameterValue(pdataset);
 			return;
 		}
@@ -302,7 +320,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(boolean); //already exists, just set it.
@@ -314,7 +332,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(integer); //already exists, just set it.
@@ -326,7 +344,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(scalar); //already exists, just set it.
@@ -338,7 +356,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(string); //already exists, just set it.
@@ -350,7 +368,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(stringarray,M); //already exists, just set it.
@@ -362,7 +380,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(IssmDoublearray,M); //already exists, just set it.
@@ -374,7 +392,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(IssmDoublearray,M,N); //already exists, just set it.
@@ -388,5 +406,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(intarray,M); //already exists, just set it.
@@ -400,5 +418,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(intarray,M,N); //already exists, just set it.
@@ -410,7 +428,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(vector); //already exists, just set it.
@@ -422,7 +440,7 @@
 
 	Param* param=NULL;
-	
-	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+
+	/*first, figure out if the param has already been created: */
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(matrix); //already exists, just set it.
@@ -436,5 +454,5 @@
 
 	/*first, figure out if the param has already been created: */
-	param=(Param*)this->FindParamObject(enum_type);
+	param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
 
 	if(param) param->SetValue(fid); //already exists, just set it.
@@ -449,5 +467,5 @@
 
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		param->UnitConversion(direction_enum);
 	}
@@ -464,5 +482,5 @@
 	for ( object=objects.begin() ; object < objects.end(); object++ ){
 
-		param=(Param*)(*object);
+		param=dynamic_cast<Param*>(*object);
 		if(param->InstanceEnum()==enum_type){
 			return (*object);
Index: /issm/trunk/src/c/Container/Parameters.h
===================================================================
--- /issm/trunk/src/c/Container/Parameters.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Parameters.h	(revision 13975)
@@ -44,5 +44,6 @@
 		void  FindParam(Matrix<IssmDouble>** pmat,int enum_type);
 		void  FindParam(FILE** pfid,int enum_type);
-		
+		void  FindParam(DataSet** pdataset, int enum_type);
+
 		void  SetParam(bool boolean,int enum_type);
 		void  SetParam(int integer,int enum_type);
Index: /issm/trunk/src/c/Container/Results.cpp
===================================================================
--- /issm/trunk/src/c/Container/Results.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Results.cpp	(revision 13975)
@@ -66,5 +66,5 @@
 /*FUNCTION Results::Write{{{*/
 void Results::Write(Parameters* parameters){
-	
+
 	int         i;
 	FILE       *fid          = NULL;
@@ -76,5 +76,5 @@
 
 	for(i=0;i<this->Size();i++){
-		ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
+		ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
 
 		/*write result to disk: */
Index: /issm/trunk/src/c/Container/Results.h
===================================================================
--- /issm/trunk/src/c/Container/Results.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Results.h	(revision 13975)
@@ -20,13 +20,11 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors*/
 		Results();
 		~Results();
-		/*}}}*/
-		/*numerics: {{{*/
+
+		/*numerics*/
 		Results* SpawnTriaResults(int* indices);
-		void Write(Parameters* parameters);
-		/*}}}*/
+		void     Write(Parameters* parameters);
 };
 #endif //ifndef _RESULTS_H_
-
Index: /issm/trunk/src/c/Container/Vertices.cpp
===================================================================
--- /issm/trunk/src/c/Container/Vertices.cpp	(revision 13974)
+++ /issm/trunk/src/c/Container/Vertices.cpp	(revision 13975)
@@ -38,71 +38,75 @@
 
 /*Numerics management*/
-/*FUNCTION Vertices::DistributeDofs{{{*/
-void  Vertices::DistributeDofs(int numberofobjects,int numberofdofsperobject){
-
-	extern int num_procs;
-	extern int my_rank;
+/*FUNCTION Vertices::DistributePids{{{*/
+void  Vertices::DistributePids(int numberofobjects){
+
+	int num_procs;
+	int my_rank;
 
 	int  i;
-	int  dofcount=0;
-	int* alldofcount=NULL;
-	int* truedofs=NULL;
-	int* alltruedofs=NULL;
-
-	/*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
+	int  pidcount    = 0;
+	int *allpidcount = NULL;
+	int *truepids    = NULL;
+	int *alltruepids = NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
+	/*Go through objects, and distribute pids locally, from 0 to numberofpidsperobject*/
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
-		vertex->DistributeDofs(&dofcount);
-	}
-
-	/* Now every object has distributed dofs, but locally, and with a dof count starting from 
-	 * 0. This means the dofs between all the cpus are not unique. We now offset the dofs of eache
-	 * cpus by the total last dofs of the previus cpu, starting from 0.
-	 * First: bet number of dofs for each cpu*/
-	alldofcount=xNew<int>(num_procs);
-	#ifdef _HAVE_MPI_
-	MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
-	MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->DistributePids(&pidcount);
+	}
+
+	/* Now every object has distributed pids, but locally, and with a pid count starting from 
+	 * 0. This means the pids between all the cpus are not unique. We now offset the pids of each
+	 * cpus by the total last pids of the previus cpu, starting from 0.
+	 * First: get number of pids for each cpu*/
+	allpidcount=xNew<int>(num_procs);
+	#ifdef _HAVE_MPI_
+	MPI_Gather(&pidcount,1,MPI_INT,allpidcount,1,MPI_INT,0,IssmComm::GetComm());
+	MPI_Bcast(allpidcount,num_procs,MPI_INT,0,IssmComm::GetComm());
 	#else
-	alldofcount[0]=dofcount;
-	#endif
-
-	/* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
-	dofcount=0;
+	allpidcount[0]=pidcount;
+	#endif
+
+	/* Every cpu should start its own pid count at the end of the pidcount from cpu-1*/
+	pidcount=0;
 	if(my_rank!=0){
 		for(i=0;i<my_rank;i++){
-			dofcount+=alldofcount[i];
+			pidcount+=allpidcount[i];
 		}
 	}
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
-		vertex->OffsetDofs(dofcount);
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->OffsetPids(pidcount);
 	}
 
 	/* Finally, remember that cpus may have skipped some objects, because they were clones. For every 
-	 * object that is not a clone, tell them to show their dofs, so that later on, they can get picked 
+	 * object that is not a clone, tell them to show their pids, so that later on, they can get picked 
 	 * up by their clones: */
-	truedofs   =xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
-	alltruedofs=xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
+	truepids   =xNewZeroInit<int>(numberofobjects);
+	alltruepids=xNewZeroInit<int>(numberofobjects);
 	for (i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
-		vertex->ShowTrueDofs(truedofs);
-	}
-	#ifdef _HAVE_MPI_
-	MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numberofobjects*numberofdofsperobject,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->ShowTruePids(truepids);
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)truepids,(void*)alltruepids,numberofobjects,MPI_INT,MPI_MAX,IssmComm::GetComm());
 	#else
-	for(i=0;i<numberofobjects*numberofdofsperobject;i++)alltruedofs[i]=truedofs[i];
-	#endif
-
-	/* Now every cpu knows the true dofs of everyone else that is not a clone*/
-	for (i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
-		vertex->UpdateCloneDofs(alltruedofs);
+	for(i=0;i<numberofobjects;i++)alltruepids[i]=truepids[i];
+	#endif
+
+	/* Now every cpu knows the true pids of everyone else that is not a clone*/
+	for(i=0;i<this->Size();i++){
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
+		vertex->UpdateClonePids(alltruepids);
 	}
 
 	/* Free ressources: */
-	xDelete<int>(alldofcount);
-	xDelete<int>(truedofs);
-	xDelete<int>(alltruedofs);
+	xDelete<int>(allpidcount);
+	xDelete<int>(truepids);
+	xDelete<int>(alltruepids);
 }
 /*}}}*/
@@ -111,8 +115,11 @@
 
 	int i;
-	extern int num_procs;
+	int num_procs;
 
 	int* ranks=NULL;
 	int* minranks=NULL;
+
+	/*recover num_procs:*/
+	num_procs=IssmComm::GetSize();
 
 	/*Allocate ranks: */
@@ -130,5 +137,5 @@
 	 * order of cpu rank. This is also why we initialized this array to num_procs.*/
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
+	MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,IssmComm::GetComm());
 	#else
 	for(i=0;i<numberofobjects;i++)minranks[i]=ranks[i];
@@ -138,5 +145,5 @@
 	for(i=0;i<this->Size();i++){
 		/*For this object, decide whether it is a clone: */
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
 		vertex->SetClone(minranks);
 	}
@@ -156,5 +163,5 @@
 
 	for(i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
 		sid=vertex->Sid();
 		if (sid>max_sid)max_sid=sid;
@@ -162,6 +169,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,IssmComm::GetComm());
 	max_sid=vertex_max_sid;
 	#endif
@@ -177,19 +184,17 @@
 void   Vertices::Ranks(int* ranks){
 
+	int my_rank;
+	int        sid;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*Go through a dataset, and for each object, report it cpu: */
-
-	int i;
-	int rank;
-	int sid;
-	
-	for(i=0;i<this->Size();i++){
-		Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
-		rank=vertex->MyRank();
+	for(int i=0;i<this->Size();i++){
+		/*Plug rank into ranks, according to id: */
+		Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
 		sid=vertex->Sid();
-		
-		/*Plug rank into ranks, according to id: */
-		ranks[sid]=rank; 
-	}
-	return;
-}
-/*}}}*/
+		ranks[sid]=my_rank; 
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/Container/Vertices.h
===================================================================
--- /issm/trunk/src/c/Container/Vertices.h	(revision 13974)
+++ /issm/trunk/src/c/Container/Vertices.h	(revision 13975)
@@ -19,15 +19,13 @@
 	public:
 
-		/*constructors, destructors: {{{*/
+		/*constructors, destructors:*/ 
 		Vertices();
 		~Vertices();
-		/*}}}*/
-		/*numerics: {{{*/
-		void  DistributeDofs(int numberofnodes,int numdofspernode);
+
+		/*numerics:*/
+		void  DistributePids(int numberofnodes);
 		void  FlagClones(int numberofnodes);
 		int   NumberOfVertices(void);
 		void  Ranks(int* ranks);
-		/*}}}*/
-
 };
 
Index: /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h
===================================================================
--- /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13974)
+++ /issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h	(revision 13975)
@@ -13,11 +13,23 @@
 	/*Model fields {{{1*/
 	AutodiffIsautodiffEnum, 
-	AutodiffDependentsEnum,
 	AutodiffNumDependentsEnum,
-	AutodiffIndependentsEnum,
+	AutodiffNumDependentObjectsEnum,
+	AutodiffDependentObjectNamesEnum,
+	AutodiffDependentObjectTypesEnum,
+	AutodiffDependentObjectIndicesEnum,
+	AutodiffDependentObjectsEnum,
 	AutodiffNumIndependentsEnum,
+	AutodiffNumIndependentObjectsEnum,
+	AutodiffIndependentObjectNamesEnum,
+	AutodiffIndependentObjectTypesEnum,
+	AutodiffIndependentObjectsEnum,
 	AutodiffJacobianEnum,
 	AutodiffXpEnum,
-	AutodiffFosForwardOutputEnum,
+	AutodiffDriverEnum,
+	AutodiffFosForwardIndexEnum,
+	AutodiffFovForwardIndicesEnum,
+	AutodiffFosReverseIndexEnum,
+	AutodiffMassFluxSegmentsPresentEnum,
+	AutodiffKeepEnum,
 	BalancethicknessSpcthicknessEnum,
 	BalancethicknessStabilizationEnum,
@@ -31,4 +43,5 @@
 	ConstantsReferencetemperatureEnum,
 	ConstantsYtsEnum,
+	DependentObjectEnum,
 	DiagnosticAbstolEnum,
 	DiagnosticIcefrontEnum,
@@ -70,4 +83,5 @@
 	HydrologySpcwatercolumnEnum,
 	HydrologyStabilizationEnum,
+	IndependentObjectEnum,
 	InversionControlParametersEnum,
 	InversionCostFunctionEnum,
@@ -143,6 +157,10 @@
 	PrognosticStabilizationEnum,
 	PrognosticVertexPairingEnum,
+	PrognosticNumRequestedOutputsEnum,
+	PrognosticRequestedOutputsEnum,
 	QmuIsdakotaEnum,
-	QmuMassFluxSegmentsEnum,
+	MassFluxSegmentsEnum,
+	MassFluxSegmentsPresentEnum,
+	QmuMassFluxSegmentsPresentEnum,
 	QmuNumberofpartitionsEnum,
 	QmuNumberofresponsesEnum,
@@ -179,4 +197,6 @@
 	SurfaceforcingsMonthlytemperaturesEnum,
 	SurfaceforcingsHcEnum,
+	SurfaceforcingsHrefEnum,
+	SurfaceforcingsSmbrefEnum,
 	SurfaceforcingsSmbPosMaxEnum,
 	SurfaceforcingsSmbPosMinEnum,
@@ -273,4 +293,5 @@
 	DofIndexingEnum,
 	DoubleInputEnum,
+	DataSetParamEnum,
 	DoubleMatArrayParamEnum,
 	DoubleMatParamEnum,
@@ -302,4 +323,5 @@
 	PentaEnum,
 	PentaP1InputEnum,
+	ProfilerEnum,
 	MatrixParamEnum,
 	VectorParamEnum,
@@ -490,4 +512,6 @@
 	OldGradientEnum,
 	OutputFilePointerEnum,
+	OutputFileNameEnum,
+	LockFileNameEnum,
 	PetscOptionsAnalysesEnum,
 	PetscOptionsStringsEnum,
Index: /issm/trunk/src/c/Makefile.am
===================================================================
--- /issm/trunk/src/c/Makefile.am	(revision 13974)
+++ /issm/trunk/src/c/Makefile.am	(revision 13975)
@@ -1,3 +1,3 @@
-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@
+AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@
 
 EXEEXT=$(ISSMEXT)
@@ -9,14 +9,5 @@
 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 WRAPPERS
 if SHAREDLIBS
 lib_LTLIBRARIES += libISSMModules.la
@@ -54,4 +45,8 @@
 					./classes/objects/Constraints/SpcTransient.cpp\
 					./classes/objects/Constraints/SpcTransient.h\
+					./classes/objects/IndependentObject.h\
+					./classes/objects/IndependentObject.cpp\
+					./classes/objects/DependentObject.h\
+					./classes/objects/DependentObject.cpp\
 					./classes/DofIndexing.h\
 					./classes/DofIndexing.cpp\
@@ -63,4 +58,7 @@
 					./classes/objects/Vertex.h\
 					./classes/objects/Vertex.cpp\
+					./classes/objects/AdolcEdf.h\
+					./classes/IssmComm.h\
+					./classes/IssmComm.cpp\
 					./classes/Hook.h\
 					./classes/Hook.cpp\
@@ -152,4 +150,8 @@
 					./classes/objects/Params/TransientParam.h\
 					./classes/objects/Params/TransientParam.cpp\
+					./classes/objects/Params/DataSetParam.h\
+					./classes/objects/Params/DataSetParam.cpp\
+					./classes/objects/Profiler.h\
+					./classes/objects/Profiler.cpp\
 					./Container/Container.h\
 					./Container/Constraints.h\
@@ -182,5 +184,4 @@
 					./shared/Matrix/matrix.h\
 					./shared/Matrix/MatrixUtils.cpp\
-					./shared/Numerics/adolc_edf.h\
 					./shared/Numerics/numerics.h\
 					./shared/Numerics/Verbosity.h\
@@ -213,10 +214,5 @@
 					./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
 					./shared/String/sharedstring.h\
-					./shared/Wrapper/wrappershared.h\
-					./shared/Wrapper/ModuleBoot.cpp\
-					./shared/Wrapper/ModuleEnd.cpp\
-					./shared/Sys/sys.h\
-					./shared/Sys/ProfilingStart.cpp\
-					./shared/Sys/ProfilingEnd.cpp\
+					./shared/String/DescriptorIndex.cpp\
 					./toolkits/metis/metisincludes.h\
 					./toolkits/issm/issmtoolkit.h\
@@ -230,4 +226,5 @@
 					./io/Disk/pfopen.cpp\
 					./io/Disk/pfclose.cpp\
+					./io/Disk/WriteLockFile.cpp\
 					./io/PrintfFunction.cpp\
 					./EnumDefinitions/EnumDefinitions.h\
@@ -279,8 +276,4 @@
 					./modules/InputArtificialNoisex/InputArtificialNoisex.h\
 					./modules/InputArtificialNoisex/InputArtificialNoisex.cpp\
-					./modules/TimeAdaptx/TimeAdaptx.h\
-					./modules/TimeAdaptx/TimeAdaptx.cpp\
-					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h\
-					./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.h\
 					./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
@@ -297,6 +290,4 @@
 					./modules/SmbGradientsx/SmbGradientsx.h\
 					./modules/SmbGradientsx/SmbGradientsx.cpp\
-					./modules/UpdateConstraintsx/UpdateConstraintsx.h\
-					./modules/UpdateConstraintsx/UpdateConstraintsx.cpp\
 					./modules/MeshPartitionx/MeshPartitionx.h\
 					./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
@@ -308,19 +299,7 @@
 					./modules/StringToEnumx/StringToEnumx.cpp\
 					./modules/StringToEnumx/StringToEnumx.h\
-					./modules/SystemMatricesx/SystemMatricesx.cpp\
-					./modules/SystemMatricesx/SystemMatricesx.h\
-					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp\
-					./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h\
 					./modules/ConstraintsStatex/ConstraintsStatex.cpp\
 					./modules/ConstraintsStatex/ConstraintsStatex.h\
 					./modules/ConstraintsStatex/ConstraintsStateLocal.h\
-					./modules/Responsex/Responsex.h\
-					./modules/Responsex/Responsex.cpp\
-					./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\
@@ -340,8 +319,11 @@
 					./solutions/convergence.cpp\
 					./solutions/ProcessArguments.cpp\
-					./solutions/WriteLockFile.cpp\
 					./solutions/ResetBoundaryConditions.cpp\
 					./solutions/AnalysisConfiguration.cpp\
+					./solutions/WrapperCorePointerFromSolutionEnum.cpp\
 					./solutions/CorePointerFromSolutionEnum.cpp\
+					./solutions/EnvironmentInit.cpp\
+					./solutions/EnvironmentFinalize.cpp\
+					./solutions/ad_core.cpp\
 					./solvers/solver_linear.cpp\
 					./solvers/solver_nonlinear.cpp\
@@ -350,6 +332,7 @@
 					./classes/objects/Options/GenericOption.h\
 					./classes/objects/Options/OptionUtilities.cpp\
-					./classes/objects/Options/OptionUtilities.h
-
+					./classes/objects/Options/OptionUtilities.h\
+					./classes/RiftStruct.cpp\
+					./classes/RiftStruct.h
 #}}}
 #DAKOTA sources  {{{
@@ -358,6 +341,4 @@
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
 					  ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
-					  ./modules/DakotaResponsesx/DakotaResponsesx.h\
-					  ./modules/DakotaResponsesx/DakotaResponsesx.cpp\
 					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
 					  ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
@@ -366,12 +347,7 @@
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
 					  ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
-					  ./modules/Dakotax/Dakotax.h\
-					  ./modules/Dakotax/Dakotax.cpp\
-					  ./modules/Dakotax/DakotaMPI_Bcast.cpp\
-					  ./modules/Dakotax/DakotaFree.cpp\
-					  ./modules/Dakotax/SpawnCore.cpp\
-					  ./modules/Dakotax/DescriptorIndex.cpp\
 					  ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
-					  ./modules/Dakotax/SpawnCoreParallel.cpp
+					  ./solutions/dakota_core.cpp\
+					  ./solutions/DakotaSpawnCore.cpp
 #}}}
 #Transient sources  {{{
@@ -437,6 +413,4 @@
 					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
 					  ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
-					  ./modules/CostFunctionx/CostFunctionx.h\
-					  ./modules/CostFunctionx/CostFunctionx.cpp\
 					  ./modules/Orthx/Orthx.h\
 					  ./modules/Orthx/Orthx.cpp\
@@ -445,6 +419,4 @@
 					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
 					  ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
-					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp\
-					  ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h\
 					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
 					  ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
@@ -505,36 +477,4 @@
 						./solutions/balancethickness_core.cpp
 #}}}
-#Responses sources  {{{
-responses_sources = ./modules/MinVelx/MinVelx.h\
-					     ./modules/MinVelx/MinVelx.cpp\
-					     ./modules/MaxVelx/MaxVelx.h\
-					     ./modules/MaxVelx/MaxVelx.cpp\
-					     ./modules/MaxAbsVxx/MaxAbsVxx.h\
-					     ./modules/MaxAbsVxx/MaxAbsVxx.cpp\
-					     ./modules/MaxAbsVyx/MaxAbsVyx.h\
-					     ./modules/MaxAbsVyx/MaxAbsVyx.cpp\
-					     ./modules/MaxAbsVzx/MaxAbsVzx.h\
-					     ./modules/MaxAbsVzx/MaxAbsVzx.cpp\
-					     ./modules/MaxVxx/MaxVxx.h\
-					     ./modules/MaxVxx/MaxVxx.cpp\
-					     ./modules/MaxVyx/MaxVyx.h\
-					     ./modules/MaxVyx/MaxVyx.cpp\
-					     ./modules/MaxVzx/MaxVzx.h\
-					     ./modules/MaxVzx/MaxVzx.cpp\
-					     ./modules/MinVxx/MinVxx.h\
-					     ./modules/MinVxx/MinVxx.cpp\
-					     ./modules/MinVyx/MinVyx.h\
-					     ./modules/MinVyx/MinVyx.cpp\
-					     ./modules/MinVzx/MinVzx.h\
-					     ./modules/MinVzx/MinVzx.cpp\
-					     ./modules/TotalSmbx/TotalSmbx.h\
-					     ./modules/TotalSmbx/TotalSmbx.cpp\
-					     ./modules/IceVolumex/IceVolumex.h\
-					     ./modules/IceVolumex/IceVolumex.cpp\
-					     ./modules/ElementResponsex/ElementResponsex.h\
-					     ./modules/ElementResponsex/ElementResponsex.cpp\
-					     ./modules/MassFluxx/MassFluxx.cpp\
-					     ./modules/MassFluxx/MassFluxx.h
-#}}}
 #Slope sources  {{{
 slope_sources =  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp\
@@ -557,4 +497,8 @@
 				    ./classes/objects/Loads/Riftfront.h\
 				    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
+#}}}
+#Android sources  {{{
+android_sources = ./android/fac.h\
+				  ./android/fac.cpp
 #}}}
 #3D sources  {{{
@@ -751,5 +695,4 @@
 					./toolkits/petsc/patches/SolverEnum.h\
 					./toolkits/petsc/patches/petscpatches.h\
-					./toolkits/petsc/patches/VecTranspose.cpp\
 					./toolkits/petsc/patches/VecToMPISerial.cpp\
 					./toolkits/petsc/patches/MatToSerial.cpp\
@@ -759,5 +702,4 @@
 					./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp\
 					./toolkits/petsc/patches/NewMat.cpp\
-					./toolkits/petsc/patches/SerialToVec.cpp\
 					./toolkits/petsc/patches/VecFree.cpp\
 					./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp\
@@ -765,10 +707,5 @@
 					./toolkits/petsc/patches/VecDuplicatePatch.cpp\
 					./toolkits/petsc/patches/KSPFree.cpp\
-					./toolkits/petsc/patches/ISFree.cpp\
 					./toolkits/petsc/patches/MatFree.cpp\
-					./toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp\
-					./toolkits/petsc/patches/VecPartition.cpp\
-					./toolkits/petsc/patches/MatPartition.cpp\
-					./toolkits/petsc/patches/MatInvert.cpp\
 					./toolkits/petsc/patches/MatMultPatch.cpp\
 					./toolkits/petsc/patches/ISSMToPetscMatrixType.cpp\
@@ -789,8 +726,5 @@
 mpi_sources= ./toolkits/mpi/mpiincludes.h\
 				./toolkits/mpi/patches/mpipatches.h\
-				./toolkits/mpi/patches/DetermineLocalSize.cpp\
-				./toolkits/mpi/patches/MPI_Upperrow.cpp\
-				./toolkits/mpi/patches/MPI_Lowerrow.cpp\
-				./toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
+				./toolkits/mpi/patches/DetermineLocalSize.cpp
 #}}}
 #Metis sources  {{{
@@ -798,36 +732,6 @@
 					./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
 #}}}
-#Python sources  {{{
-python_sources=     ./python/io/pythonio.h\
-					./python/python-binding.h\
-				    ./python/io/WritePythonData.cpp\
-				    ./python/io/CheckNumPythonArguments.cpp\
-				    ./python/io/FetchPythonData.cpp
-
-#}}}
-#Matlab sources  {{{
-matlab_sources= ./toolkits/matlab/matlabincludes.h\
-				    ./matlab/matlab-binding.h\
-				    ./matlab/io/matlabio.h\
-				    ./matlab/io/MatlabNArrayToNArray.cpp\
-				    ./matlab/io/CheckNumMatlabArguments.cpp\
-				    ./matlab/io/mxGetAssignedField.cpp\
-				    ./matlab/io/WriteMatlabData.cpp\
-				    ./matlab/io/FetchMatlabData.cpp\
-				    ./matlab/io/OptionParse.cpp\
-				    ./matlab/io/MatlabMatrixToMatrix.cpp\
-				    ./matlab/io/MatlabVectorToVector.cpp\
-					 ./matlab/io/MatlabVectorToDoubleVector.cpp\
-					 ./matlab/io/MatlabMatrixToDoubleMatrix.cpp\
-					 ./matlab/io/MatlabMatrixToSeqMat.cpp\
-					 ./matlab/io/MatlabVectorToSeqVec.cpp
-#}}}
-#Matlab and Petsc sources  {{{
-matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMat.cpp\
-					 ./matlab/io/MatlabVectorToPetscVec.cpp
-
-#}}}
 #Modules sources{{{
-module_sources= ./shared/Threads/issm_threads.h\
+modules_sources= ./shared/Threads/issm_threads.h\
 			./shared/Threads/LaunchThread.cpp\
 			./shared/Threads/PartitionRange.cpp\
@@ -842,6 +746,4 @@
 			./shared/TriMesh/SplitMeshForRifts.cpp\
 			./shared/TriMesh/TriMeshUtils.cpp\
-			./modules/AddExternalResultx/AddExternalResultx.h\
-			./modules/AddExternalResultx/AddExternalResultx.cpp\
 			./modules/Chacox/Chacox.h\
 			./modules/Chacox/Chacox.cpp\
@@ -853,4 +755,6 @@
 			./modules/TriMeshx/TriMeshx.h\
 			./modules/TriMeshx/TriMeshx.cpp\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
+			./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
 			./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
@@ -947,8 +851,4 @@
 endif
 
-if RESPONSES
-issm_sources +=  $(responses_sources)
-endif
-
 if SLOPE
 issm_sources  +=  $(slope_sources)
@@ -963,4 +863,8 @@
 endif
 
+if ANDROID
+issm_sources +=  $(android_sources)
+endif
+
 if THREED
 issm_sources +=  $(threed_sources)
@@ -973,10 +877,4 @@
 if METIS
 issm_sources +=  $(metis_sources)
-endif
-
-if PETSC
-if MATLAB
-issm_sources +=  $(matlabpetsc_sources)
-endif
 endif
 
@@ -1001,6 +899,6 @@
 endif
 
-if MODULES
-libISSMModules_a_SOURCES = $(module_sources)
+if WRAPPERS
+libISSMModules_a_SOURCES = $(modules_sources)
 libISSMModules_a_SOURCES += $(bamg_sources)
 if KRIGING
@@ -1017,17 +915,4 @@
 endif
 
-if PYTHON
-libISSMPython_a_SOURCES = $(python_sources)
-libISSMPython_a_CXXFLAGS= $(ALLCXXFLAGS)
-endif
-
-if MATLAB
-libISSMMatlab_a_SOURCES = $(matlab_sources)
-libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
-if SHAREDLIBS
-libISSMMatlab_la_SOURCES = $(libISSMMatlab_a_SOURCES)
-endif
-endif
-
 if VERSION
 AM_LDFLAGS =
@@ -1042,5 +927,13 @@
 
 #Executable {{{
+if ANDROID
+if ANDROIDEXE
 bin_PROGRAMS = issm 
+else
+bin_PROGRAMS = 
+endif
+else
+bin_PROGRAMS = issm 
+endif
 
 #Standard libraries
Index: /issm/trunk/src/c/android/fac.cpp
===================================================================
--- /issm/trunk/src/c/android/fac.cpp	(revision 13975)
+++ /issm/trunk/src/c/android/fac.cpp	(revision 13975)
@@ -0,0 +1,26 @@
+/*!\file fac.cpp
+ * \brief: implementation of the fac class
+ */
+
+/*Headers{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./fac.h"
+
+/*}}}*/
+
+long fac::factorial(long n) {
+	long f = 1;
+	long i;
+	
+	for(i = 1; i <= n; i++){
+		f *= i;
+	}
+	
+	return f;
+}
+
Index: /issm/trunk/src/c/android/fac.h
===================================================================
--- /issm/trunk/src/c/android/fac.h	(revision 13975)
+++ /issm/trunk/src/c/android/fac.h	(revision 13975)
@@ -0,0 +1,14 @@
+/*
+ * fac.h:  prototype fac class with a simple factorial routine
+ */
+
+#ifndef _FAC_H_
+#define _FAC_H_
+
+class fac {
+
+	public:
+		long factorial(long n);
+};
+
+#endif
Index: /issm/trunk/src/c/classes/AdolcEdf.h
===================================================================
--- /issm/trunk/src/c/classes/AdolcEdf.h	(revision 13975)
+++ /issm/trunk/src/c/classes/AdolcEdf.h	(revision 13975)
@@ -0,0 +1,32 @@
+/*
+ * adolc_edf.h
+ *
+ *  Created on: Jun 26, 2012
+ *      Author: utke
+ */
+
+#ifndef _ADOLC_EDF_H_
+#define _ADOLC_EDF_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+
+struct Adolc_edf {
+    ext_diff_fct *myEDF_for_solverx_p;
+    Adolc_edf() : myEDF_for_solverx_p(0) {}
+    inline friend std::ostream& operator << ( ostream&, const Adolc_edf& );
+};
+
+std::ostream& operator << ( std::ostream& out, const Adolc_edf& a) {
+    out << a.myEDF_for_solverx_p;
+    return out;
+}
+
+#endif
+
+#endif
Index: /issm/trunk/src/c/classes/DofIndexing.cpp
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/DofIndexing.cpp	(revision 13975)
@@ -10,6 +10,6 @@
 
 #include <stdio.h>
+#include <string.h>
 #include "./classes.h"
-#include <string.h>
 #include "../EnumDefinitions/EnumDefinitions.h"
 #include "../shared/shared.h"
@@ -21,15 +21,15 @@
 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;
+	this->gsize    = UNDEF;
+	this->fsize    = UNDEF;
+	this->ssize    = UNDEF;
+	this->clone    = false;
+	this->f_set    = NULL;
+	this->s_set    = NULL;
+	this->svalues  = NULL;
+	this->doftype  = NULL;
+	this->gdoflist = NULL;
+	this->fdoflist = NULL;
+	this->sdoflist = NULL;
 
 }
@@ -43,10 +43,8 @@
 DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
 
-	int i;
-	this->gsize=in->gsize;
-	this->fsize=in->fsize;
-	this->ssize=in->ssize;
-	
-	this->clone=in->clone;
+	this->gsize = in->gsize;
+	this->fsize = in->fsize;
+	this->ssize = in->ssize;
+	this->clone = in->clone;
 
 	if(this->gsize>0){
@@ -58,9 +56,9 @@
 	}
 	else{
-		this->f_set=NULL;
-		this->s_set=NULL;
-		this->svalues=NULL;
-		this->doftype=NULL;
-		this->gdoflist=NULL;
+		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;
@@ -95,8 +93,6 @@
 void DofIndexing::Init(int in_gsize,int* in_doftype){
 
-	int i;
 	this->gsize=in_gsize;
-	
-	this->clone=0;
+	this->clone=false;
 
 	/*allocate: */
@@ -109,5 +105,5 @@
 	}
 
-	for (i=0;i<this->gsize;i++){
+	for(int i=0;i<this->gsize;i++){
 		/*assume dof is free, no constraints, no rigid body constraint: */
 		this->f_set[i]=true;
@@ -151,6 +147,4 @@
 void DofIndexing::Echo(void){
 
-	int i;
-
 	_printLine_("DofIndexing:");
 	_printLine_("   gsize: " << gsize);
@@ -168,5 +162,5 @@
 	_printLine_("   ssize: " << ssize);
 	_printLine_("   clone: " << clone);
-	
+
 	_printLine_("   set membership: f,s sets ");
 	for(i=0;i<gsize;i++){
@@ -208,3 +202,2 @@
 }		
 /*}}}*/
-
Index: /issm/trunk/src/c/classes/DofIndexing.h
===================================================================
--- /issm/trunk/src/c/classes/DofIndexing.h	(revision 13974)
+++ /issm/trunk/src/c/classes/DofIndexing.h	(revision 13975)
@@ -9,28 +9,27 @@
 
 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
+		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 
+		bool 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.
+		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
-		
+		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
-
+		int *gdoflist;   //dof list in g_set
+		int *fdoflist;   //dof list in f_set
+		int *sdoflist;   //dof list in s_set
 
 		/*DofIndexing constructors, destructors {{{*/
Index: /issm/trunk/src/c/classes/FemModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/FemModel.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/FemModel.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: implementation of the FemModel object
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -13,4 +12,5 @@
 #include "../Container/Container.h"
 #include "../modules/ModelProcessorx/ModelProcessorx.h"
+#include "../solutions/solutions.h"
 #include "../io/io.h"
 #include "./classes.h"
@@ -20,70 +20,89 @@
 
 /*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
+/*FUNCTION FemModel::FemModel(int argc,char** argv){{{*/
+FemModel::FemModel(int argc,char** argv,COMM incomm){
+
+	/*configuration: */
+	int* analyses=NULL;
+	int  numanalyses;
+	int  solution_type;
+	int  ierr;
+
+	/*File names*/
+	char *lockfilename   = NULL;
+	char *binfilename    = NULL;
+	char *outbinfilename = NULL;
+	char *petscfilename  = NULL;
+	char *rootpath       = NULL;
+
+	/*First things first, store the communicator, and set it as a global variable: */
+	this->comm=incomm;
+	this->SetStaticComm();
 	
-	/*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 {{{*/
+	/*Now, initialize PETSC: */
+	#ifdef _HAVE_PETSC_
+	PETSC_COMM_WORLD=this->comm;
+	ierr=PetscInitialize(&argc,&argv,(char*)0,"");  if(ierr) _error_("Could not initialize Petsc");
+	#endif
+
+	/*Start profiler: */
+	this->profiler=new Profiler();
+	profiler->Tag(Start);
+
+	/*From command line arguments, retrieve different filenames needed to create the FemModel: */
+	ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,&rootpath,argc,argv);
+
+	/*out of solution_type, figure out types of analyses needed in the femmodel: */
+	AnalysisConfiguration(&analyses,&numanalyses,solution_type);
+
+	/*Create femmodel from input files: */
+	profiler->Tag(StartInit);
+	this->InitFromFiles(rootpath,binfilename,outbinfilename,petscfilename,lockfilename,solution_type,analyses,numanalyses);
+	profiler->Tag(FinishInit);
+
+	/*Free resources */
+	xDelete<int>(analyses);
+	xDelete<char>(lockfilename);
+	xDelete<char>(binfilename);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(petscfilename);
+	xDelete<char>(rootpath);
+
+}
+/*}}}*/
+/*FUNCTION FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
+FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
+
+	/*Call InitFromFiles. This constructor is just a wrapper: */
+	this->InitFromFiles(rootpath, inputfilename, outputfilename, petscfilename, lockfilename, in_solution_type,analyses,nummodels);
+
+}
+/*}}}*/
+/*FUNCTION FemModel::~FemModel{{{*/
 FemModel::~FemModel(){
 
 	/*Intermediary*/
-	int i;
+	FILE *output_fid;
+	char *outbinfilename = NULL;
+	char *lockfilename   = NULL;
+	bool  waitonlock     = false;
+
+	/*Close output file: */
+	this->parameters->FindParam(&output_fid,OutputFilePointerEnum); 
+	this->parameters->FindParam(&outbinfilename,OutputFileNameEnum); 
+	pfclose(output_fid,outbinfilename);
+
+	/*Write lock file if requested: */
+	this->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
+	this->parameters->FindParam(&lockfilename,LockFileNameEnum);
+	if (waitonlock>0){
+		_pprintLine_("write lock file:");
+		WriteLockFile(lockfilename);
+	}
 
 	/*Delete all the datasets: */
 	xDelete<int>(analysis_type_list);
+	xDelete<char>(outbinfilename);
+	xDelete<char>(lockfilename);
 	delete elements;
 	delete nodes;
@@ -95,4 +114,26 @@
 	delete results;
 
+	/*Before we delete the profiler, report statistics for this run: */
+	profiler->Tag(Finish);  //final tagging
+	_pprintLine_("");
+	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(StartInit,FinishInit));
+	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore));
+	_pprintLine_("");
+	_pprintLine_("   Total elapsed time:"
+			<<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
+			<<profiler->DeltaTimeModMin(Start,Finish)<<" min "
+			<<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
+			);
+	_pprintLine_("");
+
+	/*Now delete: */
+	delete profiler;
+	
+	/*Finalize PETSC for this model: */
+	#ifdef _HAVE_PETSC_
+	_pprintLine_("closing Petsc");
+	PetscFinalize(); 
+	#endif
+
 }
 /*}}}*/
@@ -111,6 +152,94 @@
 }
 /*}}}*/
-
-/*Numerics: */
+/*FUNCTION FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
+void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
+
+	/*intermediary*/
+	int         i;
+	int         analysis_type;
+	FILE       *IOMODEL = NULL;
+	FILE       *petscoptionsfid = NULL;
+	FILE       *output_fid = NULL;
+	int         my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*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);
+
+	/*Open output file once for all and add output file name and file descriptor to parameters*/
+	output_fid=pfopen(outputfilename,"wb");
+	this->parameters->AddObject(new StringParam(OutputFileNameEnum,outputfilename));
+	this->parameters->SetParam(output_fid,OutputFilePointerEnum);
+
+	/*Save lock file name for later: */
+	this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
+
+	/*Now, deal with petsc options, which need to be put into the parameters dataset: */
+	petscoptionsfid=pfopen(petscfilename,"r");
+	ParsePetscOptionsx(this->parameters,petscoptionsfid);
+	pfclose(petscoptionsfid,petscfilename);
+}
+/*}}}*/
+/*FUNCTION FemModel::OutputResults {{{*/
+void FemModel::OutputResults(void){
+
+	_pprintLine_("write results to disk:");
+
+	/*Just call the OutputResultsx module: */
+	OutputResultsx(this->elements, this->nodes, this->vertices, this->loads, this->materials, this->parameters,this->results);
+
+}
+/*}}}*/
+/*FUNCTION FemModel::SetStaticComm {{{*/
+void FemModel::SetStaticComm(void){
+
+	/*This routine sets the global communicator variable hidden inside the IssmComm 
+	 *class: */
+	IssmComm::SetComm(this->comm);
+
+}
+/*}}}*/
 /*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){{{*/
 void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){
@@ -153,7 +282,1235 @@
 /*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type){{{*/
 void FemModel::SetCurrentConfiguration(int configuration_type){
-
-	/*overload: analysis_type = configuration_type: */
 	this->SetCurrentConfiguration(configuration_type,configuration_type);
 }
 /*}}}*/
+/*FUNCTION FemModel::Solve {{{*/
+void FemModel::Solve(void){
+
+	/*profiling: */
+	bool profiling = false;
+	IssmDouble solution_time;
+	IssmDouble solution_flops;
+	IssmDouble solution_memory;
+
+	/*solution: */
+	int solution_type;
+	void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
+
+	_pprintLine_("call computational core:");
+
+	/*Retrieve solution_type from parameters: */
+	parameters->FindParam(&solution_type,SolutionTypeEnum);
+
+	/*Figure out which solution core we are going to run with the current solution type: */
+	WrapperCorePointerFromSolutionEnum(&solutioncore,this->parameters,solution_type);
+
+	/*run solutoin core: */
+	profiler->Tag(StartCore);   
+	solutioncore(this); 
+	profiler->Tag(FinishCore);
+
+	/*run AD core if needed: */
+	profiler->Tag(StartAdCore); 
+	ad_core(this);      
+	profiler->Tag(FinishAdCore);
+
+	/*some profiling results for the core: */
+	parameters->FindParam(&profiling,DebugProfilingEnum);
+	if(profiling){
+
+		solution_time=profiler->DeltaTime(StartCore,FinishCore);
+		solution_flops=profiler->DeltaFlops(StartCore,FinishCore);
+		solution_memory=profiler->Memory(FinishCore);
+
+		_pprintLine_("Solution elapsed time  : " << solution_time << "  Seconds");
+		_pprintLine_("Solution elapsed flops : " << solution_flops << "  Flops");
+		_pprintLine_("Solution memory used   : " << solution_memory << "  Bytes");
+
+		/*Add to results: */
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum, solution_time, 1, 0));
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentMemEnum, solution_memory, 1, 0));
+		results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentFlopsEnum, solution_flops, 1, 0));
+	}
+}
+/*}}}*/
+
+/*Modules:*/
+void FemModel::AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf){ /*{{{*/
+
+	/*Intermediary*/
+	int  fsize,ssize,flocalsize,slocalsize;
+	int  connectivity, numberofdofspernode;
+	int  configuration_type;
+	int  m,n,M,N;
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*output*/
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+
+	bool oldalloc=false;
+
+	/*retrieve parameters: */
+	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	this->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+
+	/*retrieve node info*/
+	fsize      = this->nodes->NumberOfDofs(configuration_type,FsetEnum);
+	ssize      = this->nodes->NumberOfDofs(configuration_type,SsetEnum);
+	flocalsize = this->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
+	slocalsize = this->nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
+
+	numberofdofspernode=this->nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	if(oldalloc){
+		if(pKff) Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
+		if(pKfs) Kfs=new Matrix<IssmDouble>(fsize,ssize,connectivity,numberofdofspernode);
+		if(pdf)  df =new Vector<IssmDouble>(fsize);
+		if(ppf)  pf =new Vector<IssmDouble>(fsize);
+	}
+	else{
+		if(pKff){
+			m=flocalsize; n=flocalsize; /*local  sizes*/
+			M=fsize;      N=fsize;      /*global sizes*/
+			this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,FsetEnum);
+			Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+			xDelete<int>(d_nnz);
+			xDelete<int>(o_nnz);
+		}
+		if(pKfs){
+			m=flocalsize; n=slocalsize; /*local  sizes*/
+			M=fsize;      N=ssize;      /*global sizes*/
+			this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,SsetEnum);
+			Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
+			xDelete<int>(d_nnz);
+			xDelete<int>(o_nnz);
+		}
+		if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
+		if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
+	}
+
+	/*Allocate output pointers*/
+	if(pKff) *pKff = Kff;
+	if(pKfs) *pKfs = Kfs;
+	if(pdf)  *pdf  = df;
+	if(ppf)  *ppf  = pf;
+}
+/*}}}*/
+void FemModel::MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum){/*{{{*/
+
+	/*Intermediary*/
+	int      i,j,k,index,offset,count;
+	int      configuration_type;
+	int      d_nz,o_nz;
+	Element *element            = NULL;
+	Load    *load               = NULL;
+	int     *head_e             = NULL;
+	int     *next_e             = NULL;
+	int     *count2offset_e     = NULL;
+	int     *head_l             = NULL;
+	int     *next_l             = NULL;
+	int     *count2offset_l     = NULL;
+	int     *sidlist            = NULL;
+
+	/*output*/
+	int *d_nnz = NULL;
+	int *o_nnz = NULL;
+
+	/*retrive parameters: */
+	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*Get vector size and number of nodes*/
+	int numnodes            = nodes->NumberOfNodes(configuration_type);
+	int numberofdofspernode = nodes->MaxNumDofs(configuration_type,GsetEnum);
+	int M                   = nodes->NumberOfDofs(configuration_type,set1enum);
+	int N                   = nodes->NumberOfDofs(configuration_type,set2enum);
+	int m                   = nodes->NumberOfDofsLocal(configuration_type,set1enum);
+	int n                   = nodes->NumberOfDofsLocal(configuration_type,set2enum);
+	int numnodesperelement  = elements->MaxNumNodes();
+	int numnodesperload     = loads->MaxNumNodes(configuration_type);
+
+	/*First, we are building chaining vectors so that we know what nodes are
+	 * connected to what elements. These vectors are such that:
+	 *   for(int i=head[id];i!=-1;i=next[i])
+	 * will loop over all the elements that are connected to the node number
+	 * id*/
+	head_e         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_e[i]=-1;
+	next_e         = xNew<int>(elements->Size()*numnodesperelement);
+	count2offset_e = xNew<int>(elements->Size()*numnodesperelement);
+
+	k=0;
+	for(i=0;i<elements->Size();i++){
+		element = dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		sidlist = xNew<int>(element->GetNumberOfNodes());
+		element->GetNodesSidList(sidlist);
+
+		for(j=0;j<element->GetNumberOfNodes();j++){
+			index = sidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_e[k]=i;
+			next_e[k]=head_e[index];
+			head_e[index]=k++;
+		}
+		for(j=0;j<numnodesperelement-element->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(sidlist);
+	}
+
+	/*Chain for loads*/
+	head_l         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_l[i]=-1;
+	next_l         = xNew<int>(loads->Size(configuration_type)*numnodesperload);
+	count2offset_l = xNew<int>(loads->Size(configuration_type)*numnodesperload);
+	k=0;
+	for(i=0;i<loads->Size();i++){
+		load = dynamic_cast<Load*>(loads->GetObjectByOffset(i));
+		if(!load->InAnalysis(configuration_type)) continue;
+		sidlist = xNew<int>(load->GetNumberOfNodes());
+		load->GetNodesSidList(sidlist);
+
+		for(j=0;j<load->GetNumberOfNodes();j++){
+			index = sidlist[j];
+			_assert_(index>=0 && index<numnodes);
+
+			count2offset_l[k]=i;
+			next_l[k]=head_l[index];
+			head_l[index]=k++;
+		}
+		for(j=0;j<numnodesperload-load->GetNumberOfNodes();j++) k++;
+
+		xDelete<int>(sidlist);
+	}
+
+	/*OK now count number of dofs and flag each nodes for each node i*/
+	bool *flags                  = xNew<bool>(numnodes);
+	int  *d_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *o_connectivity         = xNewZeroInit<int>(numnodes);
+	int  *connectivity_clone     = xNewZeroInit<int>(numnodes);
+	int  *all_connectivity_clone = xNewZeroInit<int>(numnodes);
+
+	/*Create connectivity vector*/
+	for(i=0;i<nodes->Size();i++){
+		Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+		if(node->InAnalysis(configuration_type)){
+
+			/*Reinitialize flags to 0*/
+			for(j=0;j<numnodes;j++) flags[j]=false;
+
+			/*Loop over elements that hold node number i*/
+			_assert_(head_e[node->Sid()]!=-1 || head_l[node->Sid()]!=-1);
+			for(j=head_e[node->Sid()];j!=-1;j=next_e[j]){
+				offset=count2offset_e[j];
+				element=dynamic_cast<Element*>(elements->GetObjectByOffset(offset));
+				element->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+			for(j=head_l[node->Sid()];j!=-1;j=next_l[j]){
+				offset=count2offset_l[j];
+				load=dynamic_cast<Load*>(loads->GetObjectByOffset(offset));
+				load->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
+				if(node->IsClone()){
+					connectivity_clone[node->Sid()]+=d_nz+o_nz;
+				}
+				else{
+					d_connectivity[node->Sid()]+=d_nz;
+					o_connectivity[node->Sid()]+=o_nz;
+				}
+			}
+		}
+	}
+	xDelete<bool>(flags);
+	xDelete<int>(count2offset_e);
+	xDelete<int>(head_e);
+	xDelete<int>(next_e);
+	xDelete<int>(count2offset_l);
+	xDelete<int>(head_l);
+	xDelete<int>(next_l);
+
+	/*sum over all cpus*/
+#ifdef _HAVE_MPI_
+	MPI_Allreduce((void*)connectivity_clone,(void*)all_connectivity_clone,numnodes,MPI_INT,MPI_SUM,IssmComm::GetComm());
+#endif
+	xDelete<int>(connectivity_clone);
+
+	if(set1enum==FsetEnum){
+		count=0;
+		d_nnz=xNew<int>(m);
+		o_nnz=xNew<int>(m);
+		for(i=0;i<nodes->Size();i++){
+			Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
+			if(node->InAnalysis(configuration_type) && !node->IsClone()){
+				for(j=0;j<node->indexing.fsize;j++){
+					_assert_(count<m);
+					d_nnz[count]=numberofdofspernode*(d_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					o_nnz[count]=numberofdofspernode*(o_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
+					if(d_nnz[count]>n)   d_nnz[count]=n;
+					if(o_nnz[count]>N-n) o_nnz[count]=N-n;
+					count++;
+				}
+			}
+		}
+		_assert_(m==count);
+	}
+	else{
+		_error_("STOP not implemented");
+	}
+	xDelete<int>(d_connectivity);
+	xDelete<int>(o_connectivity);
+	xDelete<int>(all_connectivity_clone);
+
+	/*Allocate ouptput pointer*/
+	*pd_nnz=d_nnz;
+	*po_nnz=o_nnz;
+
+}/*}}}*/
+void FemModel::CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax){/*{{{*/
+
+	int      i,connectivity;
+	int      numberofdofspernode;
+	int      fsize,configuration_type;
+	Element *element = NULL;
+	Load    *load    = NULL;
+	Matrix<IssmDouble>* Jff = NULL;
+
+	/*Checks*/
+	_assert_(nodes && elements);
+
+	/*Recover some parameters*/
+	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+	parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
+	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+	numberofdofspernode=nodes->MaxNumDofs(configuration_type,GsetEnum);
+
+	/*Initialize Jacobian Matrix*/
+	this->AllocateSystemMatrices(&Jff,NULL,NULL,NULL);
+
+	/*Create and assemble matrix*/
+	for(i=0;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		element->CreateJacobianMatrix(Jff);
+	}
+	for (i=0;i<loads->Size();i++){
+		load=(Load*)loads->GetObjectByOffset(i);
+		if(load->InAnalysis(configuration_type)) load->CreateJacobianMatrix(Jff);
+		if(load->InAnalysis(configuration_type)) load->PenaltyCreateJacobianMatrix(Jff,kmax);
+	}
+	Jff->Assemble();
+
+	/*Assign output pointer*/
+	*pJff=Jff;
+
+}/*}}}*/
+int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
+
+	int     i;
+	Vector<IssmDouble>*     vz        = NULL;
+	Vertex *vertex    = NULL;
+	IssmDouble *thickness = NULL;
+	IssmDouble *bed       = NULL;
+
+	/*get vertex vectors for bed and thickness: */
+	GetVectorFromInputsx(&thickness,elements,nodes, vertices, loads, materials, parameters, ThicknessEnum,VertexEnum);
+	GetVectorFromInputsx(&bed      ,elements,nodes, vertices, loads, materials, parameters, BedEnum,      VertexEnum);
+
+	/*Allocate vector*/
+	vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
+
+	/*Update verices new geometry: */
+	for (i=0;i<vertices->Size();i++){
+		vertex=(Vertex*)vertices->GetObjectByOffset(i);
+		vertex->UpdatePosition(vz,parameters,thickness,bed);
+	}
+
+	/*Assemble mesh velocity*/
+	vz->Assemble();
+
+	/*Update element inputs*/
+	InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexEnum);
+
+	/*Free ressources:*/
+	xDelete<IssmDouble>(thickness);
+	xDelete<IssmDouble>(bed);
+	xdelete(&vz);
+	return 1;
+}
+/*}}}*/
+void FemModel::UpdateConstraintsx(void){ /*{{{*/
+
+	IssmDouble time;
+	int    analysis_type;
+
+	/*retrieve parameters: */
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	parameters->FindParam(&time,TimeEnum);
+
+	/*start module: */
+	if(VerboseModule()) _pprintLine_("   Updating constraints for time: " << time);
+
+	/*First, update dof constraints in nodes, using constraints: */
+	SpcNodesx(nodes,constraints,parameters,analysis_type); 
+
+	/*Now, update degrees of freedoms: */
+	NodesDofx(nodes,parameters,analysis_type);
+
+}
+/*}}}*/
+void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor,bool process_units,int weight_index){/*{{{*/
+
+	int response_descriptor_enum=StringToEnumx(response_descriptor);
+	this->Responsex(responses, response_descriptor_enum, process_units, weight_index);
+
+}
+/*}}}*/
+void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum,bool process_units,int weight_index){/*{{{*/
+
+
+	switch (response_descriptor_enum){
+
+		#ifdef _HAVE_RESPONSES_
+		case IceVolumeEnum:              this->IceVolumex(responses,process_units); break;
+		case MinVelEnum:                 this->MinVelx(responses,process_units); break;
+		case MaxVelEnum:                 this->MaxVelx(                  responses,process_units); break;
+		case MinVxEnum:                  this->MinVxx(responses,process_units); break;
+		case MaxVxEnum:                  this->MaxVxx(                   responses,process_units); break;
+		case MaxAbsVxEnum:               this->MaxAbsVxx(                responses,process_units); break;
+		case MinVyEnum:                  this->MinVyx(responses,process_units); break;
+		case MaxVyEnum:                  this->MaxVyx(                   responses,process_units); break;
+		case MaxAbsVyEnum:               this->MaxAbsVyx(                responses,process_units); break;
+		case MinVzEnum:                  this->MinVzx(responses,process_units); break;
+		case MaxVzEnum:                  this->MaxVzx(                   responses,process_units); break;
+		case MaxAbsVzEnum:               this->MaxAbsVzx(                responses,process_units); break;
+		case MassFluxEnum:               this->MassFluxx(         responses,process_units); break;
+		case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx( responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses, process_units,weight_index); break;
+		case ThicknessAlongGradientEnum: ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case ThicknessAcrossGradientEnum:ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case TotalSmbEnum:					this->TotalSmbx(responses,process_units); break;
+		case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
+		case MaterialsRheologyBbarEnum: this->ElementResponsex(responses,MaterialsRheologyBbarEnum,process_units); break;
+		case VelEnum:                   this->ElementResponsex(responses,VelEnum,process_units); break;
+		case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
+		default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break;
+		#else
+		default: _error_("ISSM was not compiled with responses capabilities, exiting!");
+		#endif
+	}
+
+}
+/*}}}*/
+void FemModel::RequestedOutputsx(int* requested_outputs, int numoutputs){/*{{{*/
+
+
+	int      output_enum;
+	int      step;
+	IssmDouble   time;
+	IssmDouble   output_value;
+	Element *element      = NULL;
+
+	/*Get time and step*/
+	parameters->FindParam(&step,StepEnum);
+	parameters->FindParam(&time,TimeEnum);
+
+	/*retrieve Inputs*/
+	if(numoutputs){
+		for(int i=0;i<numoutputs;i++){
+			output_enum=requested_outputs[i];
+
+			switch(output_enum){
+
+				case IceVolumeEnum:
+					Responsex(&output_value,"IceVolume",false,0);
+					results->AddObject(new GenericExternalResult<double>(results->Size()+1,IceVolumeEnum,reCast<IssmPDouble>(output_value),step,time));
+					break;
+				case TotalSmbEnum:
+					Responsex(&output_value,"TotalSmb",false,0);
+					results->AddObject(new GenericExternalResult<double>(results->Size()+1,TotalSmbEnum,reCast<IssmPDouble>(output_value),step,time));
+					break;
+				case MaxVelEnum:
+					Responsex(&output_value,"MaxVel",false,0);
+					results->AddObject(new GenericExternalResult<double>(results->Size()+1,MaxVelEnum,reCast<IssmPDouble>(output_value),step,time));
+					break;
+				default:
+					/*create this output in the element inputs, and then transfer to results:*/
+					for(int j=0;j<elements->Size();j++){
+						element=(Element*)elements->GetObjectByOffset(j);
+						element->RequestedOutput(output_enum,step,time);
+					}
+					break;
+			}
+		}
+	}
+}
+/*}}}*/
+void FemModel::RequestedDependentsx(void){/*{{{*/
+
+
+	bool        isautodiff      = false;
+	IssmDouble  output_value;
+
+	int         num_dependents;
+	IssmPDouble *dependents;
+	DataSet*    dependent_objects=NULL;
+
+	/*AD mode on?: */
+	parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+		#ifdef _HAVE_ADOLC_
+		parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+		parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
+		if(num_dependents){
+			dependents=xNew<IssmPDouble>(num_dependents);
+
+			/*Go through our dependent variables, and compute the response:*/
+			for(int i=0;i<dependent_objects->Size();i++){
+				DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
+				dep->Responsex(&output_value,this);
+				output_value>>=dependents[i];
+			}
+		}
+		delete dependent_objects;
+		#else
+		_error_("Should not be requesting dependents when an AD library is not available!");
+		#endif
+	}
+}
+/*}}}*/
+void FemModel::SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax){/*{{{*/
+
+	/*intermediary: */
+	int      i;
+	int      configuration_type;
+	Element *element = NULL;
+	Load    *load    = NULL;
+
+	/*output: */
+	Matrix<IssmDouble> *Kff  = NULL;
+	Matrix<IssmDouble> *Kfs  = NULL;
+	Vector<IssmDouble> *pf   = NULL;
+	Vector<IssmDouble> *df   = NULL;
+	IssmDouble          kmax = 0;
+
+	/*Display message*/
+	if(VerboseModule()) _pprintLine_("   Generating matrices");
+
+	/*retrive parameters: */
+	this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
+
+	/*First, we might need to do a dry run to get kmax if penalties are employed*/
+	if(loads->IsPenalty(configuration_type)){
+
+		/*Allocate Kff_temp*/
+		Matrix<IssmDouble> *Kff_temp = NULL;
+		this->AllocateSystemMatrices(&Kff_temp,NULL,NULL,NULL);
+
+		/*Get complete stiffness matrix without penalties*/
+		for (i=0;i<this->elements->Size();i++){
+			element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+			element->CreateKMatrix(Kff_temp,NULL,NULL);
+		}
+		for (i=0;i<this->loads->Size();i++){
+			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
+		}
+		Kff_temp->Assemble();
+
+		/*Now, figure out maximum value of stiffness matrix, so that we can penalize it correctly: */
+		kmax=Kff_temp->Norm(NORM_INF);
+		delete Kff_temp;
+	}
+
+	/*Allocate stiffness matrices and load vector*/
+	this->AllocateSystemMatrices(&Kff,&Kfs,&df,&pf);
+
+	/*Fill stiffness matrix from elements and loads */
+	for (i=0;i<this->elements->Size();i++){
+		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->CreateKMatrix(Kff,Kfs,df);
+	}
+	for (i=0;i<this->loads->Size();i++){
+		load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
+		if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff,Kfs);
+	}
+
+	/*Fill right hand side vector, from elements and loads */
+	for (i=0;i<this->elements->Size();i++){
+		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		element->CreatePVector(pf);
+	}
+	for (i=0;i<this->loads->Size();i++){
+		load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
+		if(load->InAnalysis(configuration_type)) load->CreatePVector(pf);
+	}
+
+	/*Now deal with penalties (only in loads)*/
+	if(loads->IsPenalty(configuration_type)){
+		for (i=0;i<this->loads->Size();i++){
+			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
+		}
+		for (i=0;i<this->loads->Size();i++){
+			load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
+			if(load->InAnalysis(configuration_type)) load->PenaltyCreatePVector(pf,kmax);
+		}
+	}
+
+	/*Assemble matrices and vector*/
+	Kff->Assemble();
+	Kfs->Assemble();
+	pf->Assemble();
+	df->Assemble();
+	//Kff->AllocationInfo();
+	//Kfs->AllocationInfo();
+
+	/*Assign output pointers: */
+	if(pKff) *pKff=Kff;
+	else      xdelete(&Kff);
+	if(pKfs) *pKfs=Kfs;
+	else      xdelete(&Kfs);
+	if(ppf)  *ppf=pf;
+	else      xdelete(&pf);
+	if(pdf)  *pdf=df;
+	else      xdelete(&df);
+	if(pkmax) *pkmax=kmax;
+}
+/*}}}*/
+void FemModel::TimeAdaptx(IssmDouble* pdt){/*{{{*/
+
+	int      i;
+
+	/*output: */
+	IssmDouble   dt;
+
+	/*intermediary: */
+	Element *element     = NULL;
+	IssmDouble   min_dt      = 0;
+	IssmDouble   node_min_dt = 0;
+
+	/*Go through elements, and figure out the minimum of the time steps for each element (using CFL criterion): */
+	element=(Element*)elements->GetObjectByOffset(0); min_dt=element->TimeAdapt();
+
+	for (i=1;i<elements->Size();i++){
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		dt=element->TimeAdapt();
+		if(dt<min_dt)min_dt=dt;
+	}
+
+	/*Figure out minimum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce (&min_dt,&node_min_dt,1,MPI_DOUBLE,MPI_MIN,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_min_dt,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	min_dt=node_min_dt;
+#endif
+
+	/*Assign output pointers:*/
+	*pdt=min_dt;
+}
+/*}}}*/
+#ifdef _HAVE_RESPONSES_
+void FemModel::MassFluxx(IssmDouble* pmass_flux,bool process_units){/*{{{*/
+
+	int          i,j;
+	Element     *element       = NULL;
+	int          element_id;
+	bool         ispresent     = false;
+	IssmDouble   mass_flux     = 0;
+	IssmDouble   all_mass_flux = 0;
+	int          counter;
+	IssmDouble **array         = NULL;
+	int          M;
+	int         *mdims_array   = NULL;
+	int         *ndims_array   = NULL;
+	IssmDouble  *segments      = NULL;
+	int          num_segments;
+
+	/*First, figure out which segment to compute our mass flux on. Start with retrieving qmu_mass_flux_segments: */
+	this->parameters->FindParam(&ispresent,MassFluxSegmentsPresentEnum);
+	if(!ispresent)_error_("no mass flux segments available!");
+	this->parameters->FindParam(&array,&M,&mdims_array,&ndims_array,MassFluxSegmentsEnum);
+
+	/*Retrieve index of segments being used for MassFlux computation: */
+	parameters->FindParam(&counter,IndexEnum);
+
+	/*retrieve segments from array: */
+	segments     = array[counter-1]; //matlab to "C" indexing
+	num_segments = mdims_array[counter-1];
+
+	/*Go through segments, and then elements, and figure out which elements belong to a segment. 
+	 * When we find one, use the element to compute the mass flux on the segment: */
+	for(i=0;i<num_segments;i++){
+		element_id=reCast<int,IssmDouble>(*(segments+5*i+4));
+		for(j=0;j<elements->Size();j++){
+			element=(Element*)this->elements->GetObjectByOffset(j);
+			if (element->Id()==element_id){
+				/*We found the element which owns this segment, use it to compute the mass flux: */
+				mass_flux+=element->MassFlux(segments+5*i+0,process_units);
+				break;
+			}
+		}
+	}
+
+#ifdef _HAVE_MPI_
+	MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+	mass_flux=all_mass_flux;
+#endif
+
+	/*Free ressources:*/
+	for(i=0;i<M;i++){
+		IssmDouble* matrix=array[i];
+		xDelete<IssmDouble>(matrix);
+	}
+	xDelete<int>(mdims_array);
+	xDelete<int>(ndims_array);
+	xDelete<IssmDouble*>(array);
+
+	/*Assign output pointers: */
+	*pmass_flux=mass_flux;
+
+}/*}}}*/
+void FemModel::MaxAbsVxx(IssmDouble* pmaxabsvx,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxabsvx;
+	IssmDouble node_maxabsvx;
+	IssmDouble element_maxabsvx;
+
+	/*Go through elements, and request velocity: */
+	maxabsvx=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxAbsVx(&element_maxabsvx,process_units);
+		if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxabsvx,&node_maxabsvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxabsvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvx=node_maxabsvx;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvx=maxabsvx;
+
+}/*}}}*/
+void FemModel::MaxAbsVyx(IssmDouble* pmaxabsvy,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxabsvy;
+	IssmDouble node_maxabsvy;
+	IssmDouble element_maxabsvy;
+
+	/*Go through elements, and request velocity: */
+	maxabsvy=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxAbsVy(&element_maxabsvy,process_units);
+		if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxabsvy,&node_maxabsvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxabsvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvy=node_maxabsvy;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvy=maxabsvy;
+
+}/*}}}*/
+void FemModel::MaxAbsVzx(IssmDouble* pmaxabsvz,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxabsvz;
+	IssmDouble node_maxabsvz;
+	IssmDouble element_maxabsvz;
+
+	/*Go through elements, and request velocity: */
+	maxabsvz=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxAbsVz(&element_maxabsvz,process_units);
+		if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxabsvz,&node_maxabsvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxabsvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxabsvz=node_maxabsvz;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxabsvz=maxabsvz;
+
+}/*}}}*/
+void FemModel::MaxVelx(IssmDouble* pmaxvel,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxvel;
+	IssmDouble node_maxvel;
+	IssmDouble element_maxvel;
+
+	/*Go through elements, and request velocity: */
+	maxvel=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxVel(&element_maxvel,process_units);
+		if(element_maxvel>maxvel) maxvel=element_maxvel;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxvel,&node_maxvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvel=node_maxvel;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxvel=maxvel;
+
+}/*}}}*/
+void FemModel::MaxVxx(IssmDouble* pmaxvx,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxvx;
+	IssmDouble node_maxvx;
+	IssmDouble element_maxvx;
+
+	/*Go through elements, and request velocity: */
+	maxvx=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxVx(&element_maxvx,process_units);
+		if(element_maxvx>maxvx) maxvx=element_maxvx;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxvx,&node_maxvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvx=node_maxvx;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxvx=maxvx;
+
+}/*}}}*/
+void FemModel::MaxVyx(IssmDouble* pmaxvy,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxvy;
+	IssmDouble node_maxvy;
+	IssmDouble element_maxvy;
+
+	/*Go through elements, and request velocity: */
+	maxvy=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxVy(&element_maxvy,process_units);
+		if(element_maxvy>maxvy) maxvy=element_maxvy;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxvy,&node_maxvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvy=node_maxvy;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxvy=maxvy;
+
+}/*}}}*/
+void FemModel::MaxVzx(IssmDouble* pmaxvz,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble maxvz;
+	IssmDouble node_maxvz;
+	IssmDouble element_maxvz;
+
+	/*Go through elements, and request velocity: */
+	maxvz=-INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MaxVz(&element_maxvz,process_units);
+		if(element_maxvz>maxvz) maxvz=element_maxvz;
+	}
+
+	/*Figure out maximum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&maxvz,&node_maxvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_maxvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	maxvz=node_maxvz;
+#endif
+
+	/*Assign output pointers:*/
+	*pmaxvz=maxvz;
+
+}/*}}}*/
+void FemModel::MinVelx(IssmDouble* pminvel,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble minvel;
+	IssmDouble node_minvel;
+	IssmDouble element_minvel;
+
+	/*Go through elements, and request velocity: */
+	minvel=INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MinVel(&element_minvel,process_units);
+		if(element_minvel<minvel) minvel=element_minvel;
+	}
+
+	/*Figure out minimum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&minvel,&node_minvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_minvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvel=node_minvel;
+#endif
+
+	/*Assign output pointers:*/
+	*pminvel=minvel;
+
+}/*}}}*/
+void FemModel::MinVxx(IssmDouble* pminvx,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble minvx;
+	IssmDouble node_minvx;
+	IssmDouble element_minvx;
+
+	/*Go through elements, and request velocity: */
+	minvx=INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MinVx(&element_minvx,process_units);
+		if(element_minvx<minvx) minvx=element_minvx;
+	}
+
+	/*Figure out minimum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&minvx,&node_minvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_minvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvx=node_minvx;
+#endif
+
+	/*Assign output pointers:*/
+	*pminvx=minvx;
+
+}/*}}}*/
+void FemModel::MinVyx(IssmDouble* pminvy,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble minvy;
+	IssmDouble node_minvy;
+	IssmDouble element_minvy;
+
+	/*Go through elements, and request velocity: */
+	minvy=INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MinVy(&element_minvy,process_units);
+		if(element_minvy<minvy) minvy=element_minvy;
+	}
+
+	/*Figure out minimum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&minvy,&node_minvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_minvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvy=node_minvy;
+#endif
+
+	/*Assign output pointers:*/
+	*pminvy=minvy;
+
+}/*}}}*/
+void FemModel::MinVzx(IssmDouble* pminvz,bool process_units){/*{{{*/
+
+	int i;
+	IssmDouble minvz;
+	IssmDouble node_minvz;
+	IssmDouble element_minvz;
+
+	/*Go through elements, and request velocity: */
+	minvz=INFINITY;
+	for(i=0;i<this->elements->Size();i++){
+		Element* element=(Element*)this->elements->GetObjectByOffset(i);
+		element->MinVz(&element_minvz,process_units);
+		if(element_minvz<minvz) minvz=element_minvz;
+	}
+
+	/*Figure out minimum across the cluster: */
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&minvz,&node_minvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&node_minvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
+	minvz=node_minvz;
+#endif
+
+	/*Assign output pointers:*/
+	*pminvz=minvz;
+
+}/*}}}*/
+void FemModel::TotalSmbx(IssmDouble* pSmb,bool process_units){/*{{{*/
+
+	IssmDouble local_smb = 0;
+	IssmDouble total_smb;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		local_smb+=element->TotalSmb();
+	}
+#ifdef _HAVE_MPI_
+	MPI_Reduce(&local_smb,&total_smb,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&total_smb,1,MPI_DOUBLE,0,IssmComm::GetComm());
+#else
+	total_smb=local_smb;
+#endif
+
+	/*Assign output pointers: */
+	*pSmb=total_smb;
+
+}/*}}}*/
+void FemModel::IceVolumex(IssmDouble* pV,bool process_units){/*{{{*/
+
+	IssmDouble local_ice_volume = 0;
+	IssmDouble total_ice_volume;
+
+	for(int i=0;i<this->elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		local_ice_volume+=element->IceVolume();
+	}
+	#ifdef _HAVE_MPI_
+	MPI_Reduce(&local_ice_volume,&total_ice_volume,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&total_ice_volume,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	#else
+	total_ice_volume=local_ice_volume;
+	#endif
+
+	/*Assign output pointers: */
+	*pV=total_ice_volume;
+
+}/*}}}*/
+void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units){/*{{{*/
+
+	int found=0;
+	int sumfound=0;
+	int cpu_found=-1;
+	int index;
+	IssmDouble response;
+	Element* element=NULL;
+
+	/*retrieve element we are interested in: */
+	this->parameters->FindParam(&index,IndexEnum);
+	int my_rank=IssmComm::GetRank();
+
+	/*now, go through our elements, and retrieve the one with this id: index: */
+	for(int i=0;i<this->elements->Size();i++){
+		element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
+		if (element->Id()==index){
+			found=1;
+			cpu_found=my_rank;
+			break;
+		}
+	}
+
+	/*Broadcast whether we found the element: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
+	if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
+#endif
+
+	/*Ok, we found the element, compute responseocity: */
+	if(my_rank==cpu_found){
+		element->ElementResponse(&response,response_enum,IuToExtEnum);
+	}
+
+	/*Broadcast and plug into response: */
+#ifdef _HAVE_MPI_
+	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	MPI_Bcast(&response,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
+#endif
+
+	/*Assign output pointers: */
+	*presponse=response;
+
+}/*}}}*/
+#endif
+#ifdef _HAVE_CONTROL_
+void FemModel::ThicknessAbsGradientx( IssmDouble* pJ, 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=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
+		J+=element->ThicknessAbsGradient(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,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
+	J=J_sum;
+	#endif
+
+	/*Assign output pointers: */
+	*pJ=J;
+}
+/*}}}*/
+void FemModel::CostFunctionx(IssmDouble* pJ){/*{{{*/
+
+
+	/*Intermediary*/
+	int      num_responses;
+	Element *element       = NULL;
+	int     *responses     = NULL;
+
+	/*output: */
+	IssmDouble J,Jplus;
+
+	/*Recover parameters*/
+	parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
+	parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
+
+	/*Get response*/
+	J=0;
+	for(int i=0;i<num_responses;i++){
+		this->Responsex(&Jplus,EnumToStringx(responses[i]),false,i); //False means DO NOT process units
+		J+=Jplus;
+	}
+
+	/*Assign output pointers: */
+	xDelete<int>(responses);
+	*pJ=J;
+}
+/*}}}*/
+#endif
+#ifdef  _HAVE_DAKOTA_
+void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
+
+
+	int        i,j;
+	int        my_rank;
+	bool       process_units = true;
+
+	/*intermediary: */
+	char   root[50];
+	int    index;
+	int    npart;
+	double femmodel_response;
+	int    flag;
+	double *vertex_response   = NULL;
+	double *qmu_response      = NULL;
+	double *responses_pointer = NULL;
+
+	/*retrieve npart: */
+	parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
+	my_rank=IssmComm::GetRank();
+
+	/*save the d_responses pointer: */
+	responses_pointer=d_responses;
+
+	//watch out, we have more d_numresponses than numresponsedescriptors, because the responses have been expanded if they were scaled. 
+	//because we don't know the d_responses descriptors (the scaled ones) we can't key off them, so we will key off the responses_descriptors: */
+
+	for(i=0;i<numresponsedescriptors;i++){
+
+		flag=DescriptorIndex(root,&index,responses_descriptors[i]);
+
+		if(flag==ScaledEnum){
+
+			/*this response was scaled. pick up the response from the inputs: */
+			GetVectorFromInputsx(&vertex_response,elements,nodes, vertices, loads, materials, parameters, StringToEnumx(root),VertexEnum);
+
+			/*Now, average it onto the partition nodes: */
+			AverageOntoPartitionx(&qmu_response,elements,nodes,vertices,loads,materials,parameters,vertex_response);
+
+			/*Copy onto our dakota responses: */
+			if(my_rank==0){
+				/*plug response: */
+				for(j=0;j<npart;j++)responses_pointer[j]=qmu_response[j];
+
+				/*increment response_pointer :*/
+				responses_pointer+=npart;
+			}
+
+			/*Free ressources:*/
+			xDelete<double>(vertex_response);
+			xDelete<double>(qmu_response);
+
+		}
+		else if (flag==IndexedEnum){
+
+			/*indexed response: plug index into parameters and call response module: */
+			parameters->SetParam(index,IndexEnum);
+
+			this->Responsex(&femmodel_response,root,process_units,0);//0 is the index for weights
+
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else if (flag==NodalEnum){
+			_error_("nodal response functions not supported yet!");
+
+			/*increment response_pointer :*/
+			responses_pointer++;
+		}
+		else if (flag==RegularEnum){
+
+			/*perfectly normal response function: */
+			this->Responsex(&femmodel_response,root,process_units,0);//0 is the weight index
+
+			if(my_rank==0){
+				/*plug response: */
+				responses_pointer[0]=femmodel_response;
+
+				/*increment response_pointer :*/
+				responses_pointer++;
+			}
+		}
+		else _error_("flag type " << flag << " not supported yet for response analysis");
+	}
+
+	/*Synthesize echo: {{{*/
+	if(my_rank==0){
+		_printString_("   responses: " << d_numresponses << ": ");
+		for(i=0;i<d_numresponses-1;i++)_printString_(d_responses[i] << "|");
+		_printString_(d_responses[d_numresponses-1]);
+		_printLine_("");
+	}
+	/*}}}*/
+
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/c/classes/FemModel.h
===================================================================
--- /issm/trunk/src/c/classes/FemModel.h	(revision 13974)
+++ /issm/trunk/src/c/classes/FemModel.h	(revision 13975)
@@ -19,6 +19,7 @@
 class Loads;
 class Materials;
+class Profiler;
+class Elements;
 /*}}}*/
-
 
 class FemModel {
@@ -28,29 +29,71 @@
 	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 ...)
+		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
+
+		Profiler*    profiler;             //keep time, cpu and mem statistics while we are running.
+
+		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 
+		COMM        comm;                  //communicator for this particular model
 
 		/*constructors, destructors: */
-		FemModel(char* rootpath, char* inputfilename, char* outputfilename, const int solution_type,const int* analyses,const int nummodels);
+		FemModel(int argc,char** argv,COMM comm_init);
+		FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
 		~FemModel();
 
-		/*Methods: */
+		/*Methods:*/
+		void AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf);
+		void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax);
 		void Echo();
+		void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
+		void MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum);
+		void Solve(void);
+		void OutputResults(void);
+		void SetStaticComm();
+		void SetCurrentConfiguration(int configuration_type);
+		void SetCurrentConfiguration(int configuration_type,int analysis_type);
 
-		/*Fem: */
-		void  SetCurrentConfiguration(int configuration_type);
-		void  SetCurrentConfiguration(int configuration_type,int analysis_type);
-
+		/*Modules*/ 
+		#ifdef _HAVE_RESPONSES_
+		void MassFluxx(IssmDouble* presponse,bool process_units);
+		void MaxAbsVxx(IssmDouble* presponse,bool process_units);
+		void MaxAbsVyx(IssmDouble* presponse,bool process_units);
+		void MaxAbsVzx(IssmDouble* presponse,bool process_units);
+		void MaxVelx(IssmDouble* presponse,bool process_units);
+		void MaxVxx(IssmDouble* presponse,bool process_units);
+		void MaxVyx(IssmDouble* presponse,bool process_units);
+		void MaxVzx(IssmDouble* presponse,bool process_units);
+		void MinVelx(IssmDouble* presponse,bool process_units);
+		void MinVxx(IssmDouble* presponse,bool process_units);
+		void MinVyx(IssmDouble* presponse,bool process_units);
+		void MinVzx(IssmDouble* presponse,bool process_units);
+		void TotalSmbx(IssmDouble* pSmb,bool process_units);
+		void IceVolumex(IssmDouble* pV,bool process_units);
+		void ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units);
+		#endif
+		#ifdef  _HAVE_DAKOTA_
+		void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
+		#endif
+		void RequestedOutputsx(int* requested_outputs, int numoutputs);
+		void RequestedDependentsx(void);
+		void Responsex(IssmDouble* presponse,int response_descriptor_enum,bool process_units,int weight_index);
+		void Responsex(IssmDouble* presponse,const char* response_descriptor,bool process_units,int weight_index);
+		#ifdef _HAVE_CONTROL_
+		void CostFunctionx( IssmDouble* pJ);
+		void ThicknessAbsGradientx( IssmDouble* pJ, bool process_units,int weight_index);
+		#endif
+		void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax);
+		void TimeAdaptx(IssmDouble* pdt);
+		void UpdateConstraintsx(void);
+		int  UpdateVertexPositionsx(void);
 };
 
Index: /issm/trunk/src/c/classes/Hook.cpp
===================================================================
--- /issm/trunk/src/c/classes/Hook.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/Hook.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: implementation of the Hook object: see Hook.h for more explanations.
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -18,20 +17,15 @@
 #include "../include/include.h"
 
-
 /*Constructor/Destructors*/
 /*FUNCTION Hook::Hook(){{{*/
 Hook::Hook(){
-	this->num=0;
-	this->objects=NULL;
-	this->ids=NULL;
-	this->offsets=NULL;
-	return;
+	this->num     = 0;
+	this->objects = NULL;
+	this->ids     = NULL;
+	this->offsets = NULL;
 }
 /*}}}*/
 /*FUNCTION Hook::Hook(int* ids, int num){{{*/
 Hook::Hook(int* in_ids, int in_num){
-
-	/*Intermediaries*/
-	int i;
 
 	/*Get number of objects to hook*/
@@ -41,7 +35,7 @@
 	if (num==0){
 		/*Empty hook*/
-		this->ids=NULL;
-		this->objects=NULL;
-		this->offsets=NULL;
+		this->ids     = NULL;
+		this->objects = NULL;
+		this->offsets = NULL;
 	}
 	else{
@@ -52,8 +46,8 @@
 
 		/*Copy ids: */
-		for (i=0;i<this->num;i++){
-			this->ids[i]=in_ids[i];
-			this->objects[i]=NULL;
-			this->offsets[i]=0;
+		for(int i=0;i<this->num;i++){
+			this->ids[i]     = in_ids[i];
+			this->objects[i] = NULL;
+			this->offsets[i] = 0;
 		}
 	}
@@ -62,9 +56,7 @@
 /*FUNCTION Hook::~Hook(){{{*/
 Hook::~Hook(){
-	/*deallocate: */
 	xDelete<Object*>(this->objects);
 	xDelete<int>(this->ids);
 	xDelete<int>(this->offsets);
-	return;
 }
 /*}}}*/
@@ -121,6 +113,4 @@
 Object* Hook::copy(void){
 
-	int i;
-
 	/*output: */
 	Hook* output=NULL;
@@ -132,13 +122,13 @@
 	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];
+		output->objects = xNew<Object*>(output->num);
+		output->ids     = xNew<int>(output->num);
+		output->offsets = xNew<int>(output->num);
+	}
+
+	for(int i=0;i<output->num;i++){
+		output->objects[i] = this->objects[i];
+		output->offsets[i] = this->offsets[i];
+		output->ids[i]     = this->ids[i];
 	}
 
@@ -183,5 +173,5 @@
 		/*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
 		if(this->objects[i]==NULL){
-			this->objects[i]=(Object*)dataset->GetObjectById(this->offsets+i,this->ids[i]); //remember the offset for later on.
+			this->objects[i]=dynamic_cast<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!");
@@ -192,5 +182,5 @@
 /*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");
@@ -230,6 +220,4 @@
 /*FUNCTION Hook::Spawn{{{*/
 Hook* Hook::Spawn(int* indices, int numindices){
-
-	int i;
 
 	/*output: */
@@ -246,5 +234,5 @@
 
 	/*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");
+	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 :*/
@@ -252,12 +240,12 @@
 	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]];
+	output->objects = xNew<Object*>(output->num);
+	output->ids     = xNew<int>(output->num);
+	output->offsets = xNew<int>(output->num);
+
+	for(int 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]];
 	}
 
Index: /issm/trunk/src/c/classes/Hook.h
===================================================================
--- /issm/trunk/src/c/classes/Hook.h	(revision 13974)
+++ /issm/trunk/src/c/classes/Hook.h	(revision 13975)
@@ -19,8 +19,8 @@
 	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.
+		int      num;       //number of objects being hooked onto
+		Object **objects;   //list of object pointers
+		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:
Index: /issm/trunk/src/c/classes/IoModel.cpp
===================================================================
--- /issm/trunk/src/c/classes/IoModel.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/IoModel.cpp	(revision 13975)
@@ -17,7 +17,6 @@
 #include "./classes.h"
 #include "../io/io.h"
-#include "./Container/Parameters.h"
+#include "../Container/Parameters.h"
 #include "../shared/shared.h"
-#include "../io/io.h"
 #include "../include/include.h"
 
@@ -28,5 +27,5 @@
 	this->independents=NULL;
 	this->constants=NULL;
-	
+
 	this->my_elements=NULL;
 	this->my_nodes=NULL;
@@ -34,5 +33,5 @@
 	this->singlenodetoelementconnectivity=NULL;
 	this->numbernodetoelementconnectivity=NULL;
-	
+
 	this->nodecounter=0;
 	this->loadcounter=0;
@@ -42,5 +41,5 @@
 /*FUNCTION IoModel::IoModel(FILE*  iomodel_handle){{{*/
 IoModel::IoModel(FILE* iomodel_handle){
-	
+
 	/*First, keep track of the file handle: */
 	this->fid=iomodel_handle;
@@ -48,4 +47,13 @@
 	/*Check that Enums are Synchronized*/
 	this->CheckEnumSync();
+
+	/*Initialize data: */
+	this->data=xNew<IssmDouble*>(MaximumNumberOfEnums);
+	for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
+
+	/*If we are running in AD mode, we need to start the trace and declare our independent variables now, 
+	 *and prevent them from being erased during successive calls to iomodel->FetchConstants, iomodel->FetchData and 
+	 iomodel->DeleteData:*/
+	this->DeclareIndependents();
 
 	/*Initialize and read constants:*/
@@ -53,12 +61,4 @@
 	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;
@@ -67,5 +67,5 @@
 	this->singlenodetoelementconnectivity=NULL;
 	this->numbernodetoelementconnectivity=NULL;
-	
+
 	this->nodecounter=0;
 	this->loadcounter=0;
@@ -91,4 +91,5 @@
 	xDelete<IssmDouble*>(this->data);
 	xDelete<bool>(this->independents);
+	if(this->independent_objects)delete this->independent_objects;
 	xDelete<bool>(this->my_elements);
 	xDelete<bool>(this->my_nodes);
@@ -102,6 +103,9 @@
 void  IoModel::CheckEnumSync(void){
 
-	extern int my_rank;
+	int my_rank;
 	int record_enum = 0;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*Check that some fields have been allocated*/
@@ -182,8 +186,8 @@
 
 	/*Find constant*/
-	Param* param=(Param*)this->constants->FindParamObject(constant_enum);
+	Param* param=dynamic_cast<Param*>(this->constants->FindParamObject(constant_enum));
 	if(!param) _error_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
 
-	return (Param*)param->copy();
+	return dynamic_cast<Param*>(param->copy());
 }
 /*}}}*/
@@ -195,4 +199,68 @@
 
 	return this->data[data_enum];
+}
+/*}}}*/
+/*FUNCTION IoModel::DeclareIndependents{{{*/
+void IoModel::DeclareIndependents(void){
+
+	int         i;
+	bool        autodiff                = false;
+	int         num_independent_objects;
+
+	int *names = NULL;
+	int *types = NULL;
+
+	int         numberofvertices;
+	int         dummy;
+	bool        keep=false;
+
+	/*Initialize array detecting whether data[i] is an independent AD mode variable: */
+	this->independents=xNew<bool>(MaximumNumberOfEnums);
+	for(i=0;i<MaximumNumberOfEnums;i++) this->independents[i]=false;
+
+	this->FetchData(&autodiff,AutodiffIsautodiffEnum);
+	if(autodiff){
+
+		this->FetchData(&numberofvertices,MeshNumberofverticesEnum);
+
+		#ifdef _HAVE_ADOLC_
+
+		/*Start trace: {{{*/
+		this->FetchData(&keep,AutodiffKeepEnum);
+		if(keep)trace_on(1,1);
+		else    trace_on(1);
+
+		/*}}}*/
+		/*build dataset made of independent objects: {{{*/
+		this->independent_objects=new DataSet();
+		this->FetchData(&num_independent_objects,AutodiffNumIndependentObjectsEnum);
+		if(num_independent_objects){
+			this->FetchData(&names,&dummy,&dummy,AutodiffIndependentObjectNamesEnum);
+			this->FetchData(&types,&dummy,&dummy,AutodiffIndependentObjectTypesEnum);
+
+			/*create independent objects, and at the same time, fetch the corresponding independent variables, 
+			 *and declare them as such in ADOLC: */
+			for(i=0;i<num_independent_objects;i++){
+
+				IndependentObject* independent_object=NULL;
+				independent_object=new IndependentObject(names[i],types[i],numberofvertices);
+
+				/*add to independent_objects dataset:*/
+				this->independent_objects->AddObject(independent_object);
+
+				/*now go fetch the independent variable: */
+				independent_object->FetchIndependent(this); //supply the pointer to iomodel.
+			}
+			xDelete<int>(names);
+			xDelete<int>(types);
+		} /*}}}*/
+
+		#else
+		/*if we asked for AD computations, we have a problem!: */
+		_error_("Cannot carry out AD mode computations without support of ADOLC compiled in!");
+		#endif
+	}
+	else this->independent_objects=NULL;
+
 }
 /*}}}*/
@@ -211,5 +279,5 @@
 		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]);
@@ -227,7 +295,6 @@
 void  IoModel::FetchConstants(void){
 
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
+
 	/*record descriptions; */
 	int record_enum;
@@ -238,7 +305,11 @@
 	int  booleanint=0;
 	int  integer=0;
-	IssmPDouble scalar=0;
+	IssmPDouble pscalar=0;
+	IssmDouble scalar=0;
 	char* string=NULL;
 	int   string_size;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*Check that some fields have been allocated*/
@@ -248,5 +319,5 @@
 	/*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);
@@ -259,23 +330,23 @@
 				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: */
+				MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*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: */
+				MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*tell other cpus what we are going to do: */
 
 				/*Tell other cpus the name of the data, then branch according to the data type: */
-				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);  
-				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm());  
+				MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm());  
 				#endif
-				
+
 				switch(record_code){
 					case 1: 
@@ -283,5 +354,5 @@
 						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); 
+						MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
 						#endif
 
@@ -294,5 +365,5 @@
 						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); 
+						MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
 						#endif
 
@@ -302,9 +373,17 @@
 						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
+						/*Read the scalar and broadcast it to other cpus. However, if this record has already 
+						 * been read in DeclareIndependents, we should not re-read it, but grab it from the iomodel->data 
+						 * slots: */
+						if(this->independents[record_enum]){
+							scalar=*(this->data[record_enum]);
+						}
+						else{
+							if(fread(&pscalar,sizeof(IssmPDouble),1,this->fid)!=1) _error_("could not read scalar ");
+							#ifdef _HAVE_MPI_
+							MPI_Bcast(&pscalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
+							#endif
+							scalar=reCast<IssmDouble>(pscalar);
+						}
 
 						/*create DoubleParam: */
@@ -316,5 +395,5 @@
 						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); 
+						MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
 						#endif
 
@@ -326,5 +405,5 @@
 							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); 
+							MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
 							#endif
 						}
@@ -333,5 +412,5 @@
 							string[0]='\0';
 						}
-						
+
 						/*Add string to parameters: */
 						this->constants->AddObject(new StringParam(record_enum,string));
@@ -384,16 +463,16 @@
 	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: */
+			MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*get from cpu 0 what we are going to do: */
 			if(record_code==0){
 				break; //we are done, break from the loop
 			}
 			else{
-				MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);   //get from cpu 0 name of the data
-				MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD);  
+				MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm());   //get from cpu 0 name of the data
+				MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm());  
 				switch(record_code){
 				case 1: 
 					/*boolean. get it from cpu 0 */
-					MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
-						
+					MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
+
 					/*create BoolParam: */
 					this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to a boolean
@@ -402,6 +481,6 @@
 				case 2:
 					/*integer. get it from cpu 0 */
-					MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
-						
+					MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
+
 					/*create IntParam: */
 					this->constants->AddObject(new IntParam(record_enum,integer));
@@ -410,6 +489,6 @@
 				case 3:
 					/*scalar. get it from cpu 0 */
-					MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
-						
+					MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
+
 					/*create DoubleParam: */
 					this->constants->AddObject(new DoubleParam(record_enum,scalar));
@@ -417,5 +496,5 @@
 					break;
 				case 4: 
-					MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+					MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
 					if(string_size){
 						string=xNew<char>((string_size+1));
@@ -423,5 +502,5 @@
 
 						/*Read string from cpu 0: */
-						MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+						MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
 					}
 					else{
@@ -447,5 +526,4 @@
 				}
 
-
 			}
 		}
@@ -457,17 +535,18 @@
 void  IoModel::FetchData(bool* pboolean,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
 
 	/*output: */
 	int   booleanint;
 	int   code;
-	
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){  
@@ -475,5 +554,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -487,16 +566,18 @@
 void  IoModel::FetchData(int* pinteger,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
+	int my_rank;
 
 	/*output: */
 	int   integer;
 	int   code;
-	
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){  
@@ -505,5 +586,5 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -515,8 +596,5 @@
 void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){
 
-
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
 
 	/*output: */
@@ -524,9 +602,12 @@
 	int      code;
 
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){
@@ -534,10 +615,10 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
 	#endif
 
 	/*Assign output pointers: */
 	*pscalar=scalar;
-		 
+
 }
 /*}}}*/
@@ -545,7 +626,5 @@
 void  IoModel::FetchData(char** pstring,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
 
 	/*output: */
@@ -554,11 +633,14 @@
 	int code=0;
 
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){  
@@ -567,5 +649,5 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -580,5 +662,5 @@
 		}
 		#ifdef _HAVE_MPI_
-		MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+		MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
 		#endif
 	}
@@ -588,5 +670,4 @@
 	}
 
-
 	/*Assign output pointers: */
 	*pstring=string;
@@ -596,6 +677,5 @@
 void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
+	int my_rank;
 	int i,j;
 
@@ -607,4 +687,6 @@
 	int vector_type=0;
 
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*Set file pointer to beginning of the data: */
@@ -612,5 +694,5 @@
 
 	if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
-	
+
 	/*Now fetch: */
 
@@ -622,5 +704,5 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -629,5 +711,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm());
 	#endif
 
@@ -640,7 +722,7 @@
 			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); 
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
 		#endif
 	}
@@ -671,6 +753,5 @@
 void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
+	int my_rank;
 
 	/*output: */
@@ -680,8 +761,11 @@
 	int vector_type=0;
 
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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: */
 
@@ -692,5 +776,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -699,5 +783,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -711,5 +795,5 @@
 		}
 		#ifdef _HAVE_MPI_
-		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+		MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
 		#endif
 
@@ -736,7 +820,6 @@
 void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
+
 	int i;
 
@@ -744,15 +827,18 @@
 	int   numstrings=0;
 	char** strings=NULL;
-	
+
 	/*intermediary: */
 	char* string=NULL;
 	int   string_size;
 	int   code;
-	
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){  
@@ -760,5 +846,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numstrings,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&numstrings,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -770,10 +856,10 @@
 		/*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); 
+			MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm()); 
 			#endif
 			if(string_size){
@@ -786,5 +872,5 @@
 				}
 				#ifdef _HAVE_MPI_
-				MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD); 
+				MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm()); 
 				#endif
 			}
@@ -808,6 +894,5 @@
 	int i;
 
-	extern int my_rank;
-	extern int num_procs;
+	int my_rank;
 
 	/*output: */
@@ -821,9 +906,12 @@
 	IssmPDouble *matrix = NULL;
 	int     code;
-	
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*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){  
@@ -831,5 +919,5 @@
 	}
 	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numrecords,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&numrecords,1,MPI_INT,0,IssmComm::GetComm()); 
 	#endif
 
@@ -854,5 +942,5 @@
 			}
 			#ifdef _HAVE_MPI_
-			MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD); 
+			MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
 			#endif
 
@@ -861,5 +949,5 @@
 			}
 			#ifdef _HAVE_MPI_
-			MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD); 
+			MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
 			#endif
 
@@ -874,5 +962,5 @@
 
 				#ifdef _HAVE_MPI_
-				MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+				MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
 				#endif
 				matrices[i]=xNew<IssmDouble>(M*N);
@@ -897,7 +985,4 @@
 /*FUNCTION IoModel::FetchData(Option**  poption,int data_enum){{{*/
 void  IoModel::FetchData(Option** poption,int index){
-
-	extern int my_rank;
-	extern int num_procs;
 
 	/*output: */
@@ -955,10 +1040,10 @@
 	/*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: */
@@ -996,8 +1081,5 @@
 	int     vector_layout = 0;
 	int     counter;
-	int     nods;
-	int     nel;
 	int     numberofelements;
-
 
 	/*variables being fetched: */
@@ -1023,5 +1105,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
 					element->InputCreate((IssmDouble)boolean,vector_enum,code);
 					counter++;
@@ -1036,5 +1118,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
 					element->InputCreate((IssmDouble)integer,vector_enum,code);
 					counter++;
@@ -1049,5 +1131,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
 					element->InputCreate(scalar,vector_enum,code); 
 					counter++;
@@ -1086,5 +1168,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<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.
@@ -1124,5 +1206,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<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.
@@ -1162,5 +1244,5 @@
 			for (i=0;i<numberofelements;i++){
 				if(this->my_elements[i]){
-					Element* element=(Element*)elements->GetObjectByOffset(counter);
+					Element* element=dynamic_cast<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.
@@ -1183,7 +1265,10 @@
 void IoModel::LastIndex(int *pindex){
 
-	extern int my_rank;
+	int my_rank;
 	int        lastindex,index;
 	int        record_length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*Go find in the binary file, the position of the data we want to fetch: */
@@ -1209,5 +1294,5 @@
 	/*Broadcast code and vector type: */
 #ifdef _HAVE_MPI_
-	MPI_Bcast(&lastindex,1,MPI_INT,0,MPI_COMM_WORLD); 
+	MPI_Bcast(&lastindex,1,MPI_INT,0,IssmComm::GetComm()); 
 #endif
 
@@ -1219,12 +1304,14 @@
 FILE* IoModel::SetFilePointerToData(int* pcode,int* pvector_type, int data_enum){
 
-	extern int my_rank;
-	extern int num_procs;
-
-	int found=0;
+	int my_rank;
+
+	int found         = 0;
 	int record_enum;
 	int record_length;
-	int record_code; //1 to 7 number
-	int vector_type; //nodal or elementary
+	int record_code;       //1 to 7 number
+	int vector_type   = 0; //nodal or elementary
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*Go find in the binary file, the position of the data we want to fetch: */
@@ -1262,15 +1349,15 @@
 		}
 	}
-#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
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&found,1,MPI_INT,0,IssmComm::GetComm()); 
+	if(!found)_error_("could not find data with name " << EnumToStringx(data_enum) << " in binary file");
+	#endif
 
 	/*Broadcast code and vector type: */
-#ifdef _HAVE_MPI_
-	MPI_Bcast(&record_code,1,MPI_INT,0,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
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm()); 
+	MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm()); 
+	if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm()); 
+	#endif
 
 	/*Assign output pointers:*/
@@ -1281,95 +1368,2 @@
 }
 /*}}}*/
-/*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 13974)
+++ /issm/trunk/src/c/classes/IoModel.h	(revision 13975)
@@ -19,11 +19,11 @@
 
 	private: 
-		Parameters  *constants;   //this dataset holds all IssmDouble, int, bool and char *parameters read in from the input file.*
-	
+		Parameters *constants;   //this dataset holds all IssmDouble, int, bool and char from input
+
 	public:
-		IssmDouble **data;        //this dataset holds temporary data, memory intensive.
-		
+		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
+		FILE *fid;                               //pointer to input file
 		bool *my_elements;
 		bool *my_nodes;
@@ -36,7 +36,8 @@
 		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;
+		DataSet* independent_objects;
 
 		/*Methods*/
Index: /issm/trunk/src/c/classes/IssmComm.cpp
===================================================================
--- /issm/trunk/src/c/classes/IssmComm.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/IssmComm.cpp	(revision 13975)
@@ -0,0 +1,46 @@
+/*! \file IssmComm.cpp
+ * \brief  file containing the methods for IssmComm.h
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./IssmComm.h"
+#include "../include/types.h"
+
+void IssmComm::SetComm(COMM incomm){ /*{{{*/
+	comm=incomm;
+}/*}}}*/
+COMM IssmComm::GetComm(){  /*{{{*/
+	return comm;
+}/*}}}*/
+int IssmComm::GetRank(){  /*{{{*/
+	int my_rank = 0;
+
+	/*for matlab and python modules, comm == -1*/
+	if((int)comm==-1) return my_rank;
+
+	#ifdef _HAVE_MPI_
+	MPI_Comm_rank(comm,&my_rank);
+	#endif
+
+	return my_rank;
+
+}/*}}}*/
+int IssmComm::GetSize(){  /*{{{*/
+
+	int size = 1;
+
+	/*for matlab and python modules, comm == -1*/
+	if((int)comm==-1) return size;
+
+	#ifdef _HAVE_MPI_
+	MPI_Comm_size(comm,&size);
+	#endif
+
+	return size;
+
+}/*}}}*/
Index: /issm/trunk/src/c/classes/IssmComm.h
===================================================================
--- /issm/trunk/src/c/classes/IssmComm.h	(revision 13975)
+++ /issm/trunk/src/c/classes/IssmComm.h	(revision 13975)
@@ -0,0 +1,31 @@
+/* \file IssmComm.h
+ * \brief  create a class with a static comm, and static methods to access it
+ * This is a way of protecting access to the communicator.
+ */
+
+#ifndef _ISSM_COMM_H
+#define _ISSM_COMM_H
+
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../include/types.h"
+/*}}}*/
+
+class IssmComm {
+
+	private:
+		static COMM comm;
+
+	public:
+		static void SetComm(COMM incomm);
+		static COMM GetComm();
+		static int GetRank();
+		static int GetSize();
+};
+
+#endif  /* _ISSM_COMM_H */
Index: /issm/trunk/src/c/classes/Patch.cpp
===================================================================
--- /issm/trunk/src/c/classes/Patch.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/Patch.cpp	(revision 13975)
@@ -3,5 +3,5 @@
  */
 
-/*Include files: {{{*/
+/*Include files */
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -19,14 +19,13 @@
 #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;
+	this->numrows     = 0;
+	this->numcols     = 0;
+	this->maxvertices = 0;
+	this->maxnodes    = 0;
+	this->values      = NULL;
 }
 /*}}}*/
@@ -34,9 +33,7 @@
 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
@@ -52,7 +49,7 @@
 	}
 	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=xNew<IssmDouble>(this->numcols*this->numrows);
+		for(int i=0;i<this->numrows;i++){
+			for(int j=0;j<this->numcols;j++){
 				this->values[i*this->numcols+j]=NAN;
 			}
@@ -98,6 +95,5 @@
 
 	/*Let's remember what is on a row: 
-	 enum_type step time element_id interpolation vertices_ids nodal_values
-	 */
+	 enum_type step time element_id interpolation vertices_ids nodal_values */
 	row[0]=enum_type;
 	row[1]=(IssmDouble)step;
@@ -113,8 +109,7 @@
 void Patch::Gather(void){
 
-	int         i;
 	int         count;
-	extern int  my_rank;
-	extern int  num_procs;
+	int         my_rank;
+	int         num_procs;
 	int         total_numrows;
 	int         node_numrows;
@@ -124,8 +119,12 @@
 	#endif
 
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
+
 	/*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);
+	MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&total_numrows,1,MPI_INT,0,IssmComm::GetComm());
 	#else
 	total_numrows=this->numrows;
@@ -147,12 +146,12 @@
 	/*Now, ask other nodes to send their values: */
 	#ifdef _HAVE_MPI_
-	for (i=1;i<num_procs;i++){
+	for(int 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); 
+			MPI_Send(&this->numrows,1,MPI_INT,0,1,IssmComm::GetComm());   
+			if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,IssmComm::GetComm()); 
 		}
 		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);
+			MPI_Recv(&node_numrows,1,MPI_INT,i,1,IssmComm::GetComm(),&status); 
+			if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,IssmComm::GetComm(),&status);
 			count+=node_numrows*this->numcols;
 		}
Index: /issm/trunk/src/c/classes/Patch.h
===================================================================
--- /issm/trunk/src/c/classes/Patch.h	(revision 13974)
+++ /issm/trunk/src/c/classes/Patch.h	(revision 13975)
@@ -4,5 +4,5 @@
 
 /*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, 
@@ -12,5 +12,5 @@
 	- 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
@@ -19,5 +19,4 @@
 	   VzEnum 2  .8  2 P1  1 3 4     4.5 3.2  2.5
 */
-
 
 #ifndef _PATCH_H_
@@ -29,10 +28,9 @@
 	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
+		int         numrows;       //number of results held in Patch object
+		int         numcols;       //number of columns
+		int         maxvertices;   //largest amount of vertices on a given element, determined by geometry
+		int         maxnodes;      //the largest amout of nodes on a given element, determined by interpolation
+		IssmDouble *values;        //result values
 
 		Patch();
Index: /issm/trunk/src/c/classes/RiftStruct.cpp
===================================================================
--- /issm/trunk/src/c/classes/RiftStruct.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/RiftStruct.cpp	(revision 13975)
@@ -0,0 +1,95 @@
+/*!\file RiftStruct.c
+ * \brief: implementation of the RiftStruct object
+ */
+
+#include "./classes.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+
+/*RiftStruct constructors and destructor*/
+RiftStruct::RiftStruct(void){/*{{{*/
+
+	this->numrifts             = 0;
+	this->riftsnumsegments     = NULL;
+	this->riftssegments        = NULL;
+	this->riftsnumpairs        = NULL;
+	this->riftspairs           = NULL;
+	this->riftsnumpenaltypairs = NULL;
+	this->riftspenaltypairs    = NULL;
+	this->riftstips            = NULL;
+	this->state                = NULL;
+
+}/*}}}*/
+RiftStruct::RiftStruct(int numrifts_in,int *riftsnumsegments_in,double **riftssegments_in,int *riftsnumpairs_in,double **riftspairs_in,int *riftsnumpenaltypairs_in,double **riftspenaltypairs_in,double* riftstips_in){/*{{{*/
+
+	int i;
+
+	/*numrifts*/
+	this->numrifts = numrifts_in;
+	if(!numrifts_in) return;
+
+	/*riftsnumsegments*/
+	_assert_(riftsnumsegments_in);
+	this->riftsnumsegments=xNew<int>(numrifts_in);
+	xMemCpy<int>(this->riftsnumsegments,riftsnumsegments_in,numrifts_in);
+
+	/*riftssegments*/
+	_assert_(riftssegments_in);
+	this->riftssegments=xNew<double*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->riftssegments[i]=xNew<double>(riftsnumsegments_in[i]*3);
+		xMemCpy<double>(this->riftssegments[i],riftssegments_in[i],riftsnumsegments_in[i]*3);
+	}
+
+	/*riftsnumpairs*/
+	_assert_(riftsnumpairs_in);
+	this->riftsnumpairs=xNew<int>(numrifts_in);
+	xMemCpy<int>(this->riftsnumpairs,riftsnumpairs_in,numrifts_in);
+
+	/*riftspairs*/
+	_assert_(riftspairs_in);
+	this->riftspairs=xNew<double*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->riftspairs[i]=xNew<double>(riftsnumpairs_in[i]*2);
+		xMemCpy<double>(this->riftspairs[i],riftspairs_in[i],riftsnumpairs_in[i]*2);
+	}
+
+	/*riftsnumpenaltypairs*/
+	_assert_(riftsnumpenaltypairs_in);
+	this->riftsnumpenaltypairs=xNew<int>(numrifts_in);
+	xMemCpy<int>(this->riftsnumpenaltypairs,riftsnumpenaltypairs_in,numrifts_in);
+
+	/*riftspenaltypairs*/
+	_assert_(riftspenaltypairs_in);
+	this->riftspenaltypairs=xNew<double*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->riftspenaltypairs[i]=xNew<double>(riftsnumpenaltypairs_in[i]*7);
+		xMemCpy<double>(this->riftspenaltypairs[i],riftspenaltypairs_in[i],riftsnumpenaltypairs_in[i]*7);
+	}
+
+	/*riftstips*/
+	_assert_(riftstips_in);
+	this->riftstips=xNew<double>(2*numrifts_in);
+	xMemCpy<double>(this->riftstips,riftstips_in,2*numrifts_in);
+
+	/*state*/
+	this->state=xNew<double*>(numrifts_in);
+	for(i=0;i<numrifts_in;i++){
+		this->state[i]=xNew<double>(riftsnumpenaltypairs_in[i]);
+		for(int j=0;j<riftsnumpenaltypairs_in[i];j++) (this->state[i])[j]=FreeEnum;
+	}
+
+}/*}}}*/
+RiftStruct::~RiftStruct(void){/*{{{*/
+
+	xDelete<int>(this->riftsnumsegments);
+	xDelete<double*>(this->riftssegments);
+	xDelete<int>(this->riftsnumpairs);
+	xDelete<double*>(this->riftspairs);
+	xDelete<int>(this->riftsnumpenaltypairs);
+	xDelete<double*>(this->riftspenaltypairs);
+	xDelete<double>(this->riftstips);
+	xDelete<double*>(this->state);
+
+}/*}}}*/
Index: /issm/trunk/src/c/classes/RiftStruct.h
===================================================================
--- /issm/trunk/src/c/classes/RiftStruct.h	(revision 13975)
+++ /issm/trunk/src/c/classes/RiftStruct.h	(revision 13975)
@@ -0,0 +1,26 @@
+/*!\file:  RiftStruct.h
+ * \brief place holder for Rift Structure in mex module
+ */ 
+
+#ifndef _RIFTSTRUCT_H_
+#define _RIFTSTRUCT_H_
+
+class RiftStruct{
+
+	public:
+		int      numrifts;
+		double **riftssegments;
+		int     *riftsnumsegments;
+		double **riftspairs;
+		int     *riftsnumpairs;
+		double **riftspenaltypairs;
+		int     *riftsnumpenaltypairs;
+		double  *riftstips;
+		double **state;
+
+		RiftStruct();
+		RiftStruct(int numrifts_in,int *riftsnumsegments_in,double **riftssegments_in,int *riftsnumpairs_in,double **riftspairs_in,int *riftsnumpenaltypairs_in,double **riftspenaltypairs_in,double* riftstips_in);
+		~RiftStruct();
+};
+
+#endif
Index: /issm/trunk/src/c/classes/Update.h
===================================================================
--- /issm/trunk/src/c/classes/Update.h	(revision 13974)
+++ /issm/trunk/src/c/classes/Update.h	(revision 13975)
@@ -7,7 +7,6 @@
 
 /*Headers:*/
-/*{{{*/
 #include "../shared/shared.h"
-/*}}}*/
+class IoModel;
 
 class Update{
@@ -33,3 +32,2 @@
 
 #endif //ifndef _UPDATE_H_
-
Index: /issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp	(revision 13975)
@@ -8,5 +8,4 @@
 
 namespace bamg {
-
 
 	/*Constructors/Destructors*/
Index: /issm/trunk/src/c/classes/bamg/AdjacentTriangle.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/AdjacentTriangle.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/AdjacentTriangle.h	(revision 13975)
@@ -44,3 +44,2 @@
 }
 #endif
-
Index: /issm/trunk/src/c/classes/bamg/BamgGeom.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgGeom.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgGeom.cpp	(revision 13975)
@@ -1,4 +1,4 @@
 #include <stdio.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../io/io.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/bamg/BamgMesh.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgMesh.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgMesh.cpp	(revision 13975)
@@ -1,4 +1,4 @@
 #include <stdio.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../io/io.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/bamg/BamgOpts.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgOpts.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgOpts.cpp	(revision 13975)
@@ -2,5 +2,5 @@
 #include "../../shared/shared.h"
 #include "../../include/include.h"
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../io/io.h"
 
Index: /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp	(revision 13975)
@@ -3,5 +3,5 @@
 #include <stdlib.h>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 
 namespace bamg {
@@ -428,5 +428,4 @@
 		  }
 
-
 		if ( n0 > 0) 
 		  {  
Index: /issm/trunk/src/c/classes/bamg/BamgQuadtree.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgQuadtree.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgQuadtree.h	(revision 13975)
@@ -34,5 +34,4 @@
 					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"); };
Index: /issm/trunk/src/c/classes/bamg/BamgVertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/BamgVertex.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/BamgVertex.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 #include <ctime>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 
 namespace bamg {
Index: /issm/trunk/src/c/classes/bamg/Direction.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Direction.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Direction.h	(revision 13975)
@@ -19,3 +19,2 @@
 }
 #endif
-
Index: /issm/trunk/src/c/classes/bamg/Edge.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Edge.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Edge.h	(revision 13975)
@@ -12,5 +12,5 @@
 	//classes
 	class Mesh;
-	
+
 	class Edge {
 
@@ -36,3 +36,2 @@
 }
 #endif
-
Index: /issm/trunk/src/c/classes/bamg/EigenMetric.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/EigenMetric.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/EigenMetric.cpp	(revision 13975)
@@ -29,5 +29,4 @@
 		b=-a11-a22;
 		delta=b*b - 4*(a11*a22-a21*a21);
-
 
 		/*Compute norm of M to avoid round off errors*/
Index: /issm/trunk/src/c/classes/bamg/Geometry.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Geometry.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Geometry.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 #include <ctime>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../include/include.h"
 #include "../../shared/Exceptions/exceptions.h"
@@ -68,5 +68,5 @@
 
 		double Hmin = HUGE_VAL;// the infinie value 
-		int i,j,k,n,i0,i1,i2,i3;
+		int i,j,n,i0,i1,i2,i3;
 
 		/*initialize some variables*/
@@ -173,5 +173,5 @@
 			}
 			delete [] verticeslength;
-			
+
 		}
 		else{
@@ -499,13 +499,11 @@
 		/*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;
+		long          i          ,j,k;
+		long         *head_v   = new long[nbv];
+		long         *next_p   = new long[2 *nbe];
+		float        *eangle   = new float[nbe];
+		double        eps      = 1e-20;
+		BamgQuadtree  quadtree;                            // build quadtree to find duplicates
+		BamgVertex   *v0       = vertices;
 
 		k=0;
@@ -869,5 +867,5 @@
 		directionge[bge]=1;
 
-		while (eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){ 
+		while(eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){ 
 			if (bge<=0) {
 				if(NbTry) {
@@ -904,5 +902,4 @@
 			_assert_(tge>=0 && tge<=mxe);
 		}
-
 
 		if ((*eg0)(direction0)==(GeomVertex*)vg0)
Index: /issm/trunk/src/c/classes/bamg/Geometry.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/Geometry.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Geometry.h	(revision 13975)
@@ -64,5 +64,5 @@
 			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 13974)
+++ /issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 #include <ctime>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 
 namespace bamg {
@@ -319,6 +319,4 @@
 				ilast=NewItem(t,ba[0],ba[1],ba[2]); }
 		}  //  outside departure
-
-
 
 		// recherche the intersection of [a,b] with Bh Mesh.
@@ -392,5 +390,4 @@
 				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);
Index: /issm/trunk/src/c/classes/bamg/Mesh.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Mesh.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Mesh.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 #include <ctime>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 
 namespace bamg {
@@ -201,5 +201,4 @@
 			 }
 
-
 		  if(nbe)
 			edges = new Edge[nbe];
@@ -270,5 +269,5 @@
 		double Hmin = HUGE_VAL;// the infinie value 
 		long i1,i2,i3;
-		long i,j;
+		long i;
 		Metric M1(1);
 		int verbose=0;
@@ -386,5 +385,5 @@
 		if(bamgmesh->Quadrilaterals){
 			if(verbose>5) _printLine_("      processing Quadrilaterals");
-			long i1,i2,i3,i4,iref;
+			long i1,i2,i3,i4;
 			triangles =new Triangle[nbt];
 			for (i=0;i<bamgmesh->QuadrilateralsSize[0];i++){
@@ -1009,9 +1008,9 @@
 
 		/*Intermediary*/
-		int i,k,num;
-		int verbose=0;
+		int i,k;
 
 		/*output*/
 		int* index=NULL;
+		int  num=0;
 
 		/*Get number of triangles*/
@@ -1024,5 +1023,4 @@
 		if (k){
 			index=xNew<int>(3*k);
-			num=0;
 			for (i=0;i<nbt;i++){
 				Triangle &t=triangles[i];
@@ -1245,5 +1243,4 @@
 		tt[2]->SetSingleVertexToTriangleConnectivity();
 
-
 		// swap if the point s is on a edge
 		if(izerodet>=0) {
@@ -1574,5 +1571,5 @@
 		//initialize subdomains[isd].head as 0
 		for (isd=0;isd<nbsubdomains;isd++) subdomains[isd].head =0;
-		  
+
 		k=0;
 		for (it=0;it<nbt;it++){
@@ -2539,5 +2536,4 @@
 			delete [] HeapArete;
 			delete [] HeapTriangle;
-
 
 			if (OutSide|| !Gh.subdomains || !Gh.nbsubdomains ) 
@@ -2695,5 +2691,4 @@
 					nbsubdomains=inew;}
 
-
 					for (it=0;it<nbt;it++)
 					 if ( mark[it] ==-1 ) 
@@ -3075,5 +3070,4 @@
 			if (verbose>5) _printLine_("   do nothing: costheta > 1");
 		}
-
 
 			long nbqq = (nbt*3)/2;
@@ -4273,5 +4267,4 @@
 			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])));
@@ -4343,5 +4336,4 @@
 		nbv = k;
 
-
 		kedge = new long[3*nbt+1];
 		ksplitarray = new long[nbt+1];
@@ -4412,5 +4404,4 @@
 				const Triangle & tt = ta;
 
-
 				const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
 				const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
@@ -4648,5 +4639,4 @@
 		  BTh.vertices[i].m =  BTh.vertices[i].m*2.;
 
-
 		ret = 2;
 		if (nbt>= maxnbt) goto Error; // bug 
@@ -4963,5 +4953,5 @@
 
 		/*Intermediaries*/
-		int                i,j,k;
+		int                i,k;
 		int                nbcurves    = 0;
 		int                NbNewPoints,NbEdgeCurve;
@@ -5001,5 +4991,5 @@
 				_assert_(nbv<maxnbv);
 				vertices[nbv]=Gh[i];
-				
+
 				//Add pointer from geometry (Gh) to vertex from mesh (Th)
 				Gh[i].MeshVertexHook=vertices+nbv;
@@ -5196,5 +5186,5 @@
 										va = vb;
 									}
-									
+
 									/*We just added one edge to the curve: Go to the next one*/
 									lcurve = lcurveb;
@@ -5371,5 +5361,5 @@
 					/*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");
@@ -5419,5 +5409,5 @@
 				/*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) 
@@ -5536,5 +5526,4 @@
 						}// for(;;) end of the curve
 					}
-
 
 					if (phase){ // construction of the last edge
@@ -5787,5 +5776,4 @@
 		BamgVertex & s2= (*t2)[OppositeVertex[a2]];
 
-
 		Icoor2 dets2 = det(*pva,*pvb,s2);
 		Icoor2 det1=t1->det , det2=t2->det ;
Index: /issm/trunk/src/c/classes/bamg/Metric.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Metric.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Metric.cpp	(revision 13975)
@@ -16,9 +16,9 @@
 	/*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 ){{{*/ 
Index: /issm/trunk/src/c/classes/bamg/R2.h
===================================================================
--- /issm/trunk/src/c/classes/bamg/R2.h	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/R2.h	(revision 13975)
@@ -39,9 +39,4 @@
 	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:
 
Index: /issm/trunk/src/c/classes/bamg/SetOfE4.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/SetOfE4.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/SetOfE4.cpp	(revision 13975)
@@ -1,3 +1,3 @@
-#include "../objects.h"
+#include "../objects/objects.h"
 
 using namespace std;
Index: /issm/trunk/src/c/classes/bamg/Triangle.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/Triangle.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/Triangle.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 #include <ctime>
 
-#include "../objects.h"
+#include "../objects/objects.h"
 
 namespace bamg {
@@ -424,5 +424,4 @@
 									 sinb12 = double(det2),
 									 sinba2 = double(t2->det);
-
 
 						 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
Index: /issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp	(revision 13975)
@@ -17,5 +17,5 @@
 	/*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{*/
 	VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
-	
+
 	}/*}}}*/
 
Index: /issm/trunk/src/c/classes/classes.h
===================================================================
--- /issm/trunk/src/c/classes/classes.h	(revision 13974)
+++ /issm/trunk/src/c/classes/classes.h	(revision 13975)
@@ -30,4 +30,7 @@
 #include "./OptArgs.h"
 #include "./OptPars.h"
+#include "./AdolcEdf.h"
+#include "./IssmComm.h"
+#include "./RiftStruct.h"
 
 #endif
Index: /issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp
===================================================================
--- /issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp	(revision 13975)
@@ -15,5 +15,4 @@
  */ 
 
-
 #ifdef HAVE_CONFIG_H
 	#include <config.h>
@@ -25,6 +24,6 @@
 #include "../../shared/shared.h"
 #include "../../include/include.h"
+#include "../../solutions/solutions.h"
 #include "../classes.h"
-#include "../../modules/Dakotax/Dakotax.h"
 
 /*Standard includes: */
@@ -34,25 +33,22 @@
 
 //Dakota headers
-#include "DakotaResponse.H"
-#include "ParamResponsePair.H"
-#include "DakotaPlugin.h"
-#include "system_defs.h"
-#include "ProblemDescDB.H"
-#include "ParallelLibrary.H"
+#include <DakotaResponse.H>
+#include <ParamResponsePair.H>
+#include <system_defs.h>
+#include <ProblemDescDB.H>
+#include <ParallelLibrary.H>
+#include "./DakotaPlugin.h"
 
 namespace SIM {
 
-//constructor
-DakotaPlugin::DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){
-
+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) {
+}/*}}}*/
+DakotaPlugin::~DakotaPlugin(){/*{{{*/
+	/* Virtual destructor handles referenceCount at Interface level. */ 
+}/*}}}*/
+int DakotaPlugin::derived_map_ac(const Dakota::String& driver){/*{{{*/
 
 	int i;
@@ -80,5 +76,4 @@
 		memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
 
-		
 		variable_descriptors[i]=variable_descriptor;
 	}
@@ -88,5 +83,5 @@
 
 	/*run core solution: */
-	SpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
+	DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
 
 	/*populate responses: */
@@ -94,5 +89,4 @@
 		fnVals[i]=responses[i];
 	}
-
 
 	/*Free ressources:*/
@@ -106,13 +100,10 @@
 
 	return 0;
-}
-  
-
-int DakotaPlugin::GetCounter(){
+}/*}}}*/
+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 13974)
+++ /issm/trunk/src/c/classes/dakota/DakotaPlugin.h	(revision 13975)
@@ -5,13 +5,10 @@
 #define _DAKOTAPLUGIN_H
 
-
 #ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
 
 /*Headers:*/
-/*{{{*/
-#include "DirectApplicInterface.H"
+#include <DirectApplicInterface.H>
 #include "../../toolkits/toolkits.h"
 #include "../../classes/classes.h"
-/*}}}*/
 
 namespace SIM {
@@ -49,4 +46,3 @@
 #endif //only works if dakota library has been compiled in.
 
-
 #endif
Index: /issm/trunk/src/c/classes/gauss/GaussPenta.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 13974)
+++ /issm/trunk/src/c/classes/gauss/GaussPenta.h	(revision 13975)
@@ -28,5 +28,5 @@
 		double coord3;
 		double coord4;
-		
+
 	public:
 
Index: /issm/trunk/src/c/classes/gauss/GaussTria.h
===================================================================
--- /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 13974)
+++ /issm/trunk/src/c/classes/gauss/GaussTria.h	(revision 13975)
@@ -25,5 +25,5 @@
 		IssmDouble coord2;
 		IssmDouble coord3;
-		
+
 	public:
 
Index: /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 #include <stdio.h>
 #include <string.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/kriging/ExponentialVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/ExponentialVariogram.h	(revision 13975)
@@ -25,5 +25,4 @@
 		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");};
Index: /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 #include <stdio.h>
 #include <string.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/kriging/GaussianVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/GaussianVariogram.h	(revision 13975)
@@ -26,5 +26,4 @@
 		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");};
Index: /issm/trunk/src/c/classes/kriging/Observation.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/Observation.cpp	(revision 13975)
@@ -4,5 +4,5 @@
 
 #include <stdlib.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 
 /*Observation constructors and destructor*/
@@ -35,6 +35,4 @@
 void Observation::Echo(void){
 
-	int  bit;
-
 	_printLine_("Observation");
 	_printLine_("   index : " << this->index);
Index: /issm/trunk/src/c/classes/kriging/Observation.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Observation.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/Observation.h	(revision 13975)
@@ -26,5 +26,4 @@
 		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"); };
Index: /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 #include <stdio.h>
 #include <string.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/kriging/PowerVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/PowerVariogram.h	(revision 13975)
@@ -25,5 +25,4 @@
 		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");};
Index: /issm/trunk/src/c/classes/kriging/Quadtree.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.cpp	(revision 13975)
@@ -1,3 +1,3 @@
-#include "../objects.h"
+#include "../objects/objects.h"
 
 /*DOCUMENTATION What is a Quadtree? {{{
Index: /issm/trunk/src/c/classes/kriging/Quadtree.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/Quadtree.h	(revision 13975)
@@ -29,5 +29,4 @@
 				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"); };
Index: /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 #include <stdio.h>
 #include <string.h>
-#include "../objects.h"
+#include "../objects/objects.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "../../shared/shared.h"
Index: /issm/trunk/src/c/classes/kriging/SphericalVariogram.h
===================================================================
--- /issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 13974)
+++ /issm/trunk/src/c/classes/kriging/SphericalVariogram.h	(revision 13975)
@@ -25,5 +25,4 @@
 		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");};
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.cpp	(revision 13975)
@@ -230,5 +230,5 @@
 /*FUNCTION ElementMatrix::~ElementMatrix(){{{*/
 ElementMatrix::~ElementMatrix(){
-	
+
 	xDelete<IssmDouble>(this->values);
 	xDelete<int>(this->gglobaldoflist);
@@ -278,5 +278,4 @@
 		}
 
-
 		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: */
Index: /issm/trunk/src/c/classes/matrix/ElementMatrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/ElementMatrix.h	(revision 13975)
@@ -22,5 +22,5 @@
 
 	public:
-	
+
 		int      nrows;
 		int      ncols;
Index: /issm/trunk/src/c/classes/matrix/ElementVector.cpp
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.cpp	(revision 13975)
@@ -36,5 +36,5 @@
 	/*intermediaries*/
 	int i,j,counter;
-	int gsize,fsize,ssize;
+	int gsize,fsize;
 	int* P=NULL;
 	bool found;
@@ -139,5 +139,5 @@
 	/*fill values with 0: */
 	this->values=xNewZeroInit<IssmDouble>(this->nrows);
-	
+
 	/*g list*/
 	this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
@@ -151,5 +151,5 @@
 /*FUNCTION ElementVector::~ElementVector(){{{*/
 ElementVector::~ElementVector(){
-	
+
 	xDelete<IssmDouble>(this->values);
 	xDelete<int>(this->gglobaldoflist);
@@ -181,5 +181,5 @@
 		xDelete<IssmDouble>(localvalues);
 	}
-	
+
 }
 /*}}}*/
@@ -219,5 +219,6 @@
 void ElementVector::Echo(void){
 
-	int i,j;
+	int i;
+
 	_printLine_("Element Vector echo:");
 	_printLine_("   nrows: " << nrows);
Index: /issm/trunk/src/c/classes/matrix/ElementVector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/ElementVector.h	(revision 13975)
@@ -22,8 +22,8 @@
 
 	public:
-	
+
 		int      nrows;
 		IssmDouble*  values;
-		
+
 		//gset
 		int*     gglobaldoflist;
@@ -33,5 +33,5 @@
 		int*     flocaldoflist;
 		int*     fglobaldoflist;
-		
+
 		/*ElementVector constructors, destructors {{{*/
 		ElementVector();
@@ -51,3 +51,2 @@
 };
 #endif //#ifndef _ELEMENT_VECTOR_H_
-
Index: /issm/trunk/src/c/classes/matrix/Matrix.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Matrix.h	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/Matrix.h	(revision 13975)
@@ -76,4 +76,31 @@
 		}
 		/*}}}*/
+		/*FUNCTION Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int type){{{*/
+		#ifdef _HAVE_PETSC_
+		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=PetscMatType){
+		#else
+		Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=SeqMatType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pmatrix=NULL;
+			#endif
+			smatrix=NULL;
+			type=in_type;
+
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix=new PetscMat(m,n,M,N,d_nnz,o_nnz);
+				#else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+				#endif
+			}
+			else if(type==SeqMatType){
+				this->smatrix=new SeqMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
 		/*FUNCTION Matrix(int M,int N,IssmDouble sparsity,int in_type){{{*/
 		#ifdef _HAVE_PETSC_
@@ -163,6 +190,4 @@
 				#ifdef _HAVE_PETSC_
 				delete this->pmatrix;
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 				#endif
 			}
@@ -170,5 +195,4 @@
 				delete this->smatrix;
 			}
-			else _error_("Matrix type: " << type << " not supported yet!");
 
 		}
@@ -192,4 +216,17 @@
 		}
 		/*}}}*/
+		/*FUNCTION AllocationInfo{{{*/
+		void AllocationInfo(void){
+			_assert_(this);
+			if(type==PetscMatType){
+				#ifdef _HAVE_PETSC_
+				this->pmatrix->AllocationInfo();
+				#endif
+			}
+			else if(type==SeqMatType){
+				//this->smatrix->AllocationInfo();
+			}
+			else _error_("Matrix type: " << type << " not supported yet!");
+		}/*}}}*/
 		/*FUNCTION Assemble{{{*/
 		void Assemble(void){
@@ -274,7 +311,5 @@
 		Matrix* Duplicate(void){
 
-			Matrix* output=NULL;
-
-			output=new Matrix();
+			Matrix* output=new Matrix();
 
 			if(type==PetscMatType){
@@ -306,5 +341,4 @@
 			else _error_("Matrix type: " << type << " not supported yet!");
 
-
 			return output;
 		}
Index: /issm/trunk/src/c/classes/matrix/Vector.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/Vector.h	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/Vector.h	(revision 13975)
@@ -61,5 +61,4 @@
 			type=in_type;
 
-
 			if(type==PetscVecType){
 			#ifdef _HAVE_PETSC_
@@ -71,4 +70,31 @@
 			else if(type==SeqVecType){
 				this->svector=new SeqVec<doubletype>(M,fromlocalsize);
+			}
+			else _error_("Vector type: " << type << " not supported yet!");
+
+		}
+		/*}}}*/
+		/*FUNCTION Vector(int m,int M,int in_type){{{*/
+		#ifdef _HAVE_PETSC_
+		Vector(int m,int M,int in_type=PetscVecType){
+		#else
+		Vector(int m,int M,int in_type=SeqVecType){
+		#endif
+
+			#ifdef _HAVE_PETSC_
+			pvector=NULL;
+			#endif
+			svector=NULL;
+			type=in_type;
+
+			if(type==PetscVecType){
+			#ifdef _HAVE_PETSC_
+				this->pvector=new PetscVec(m,M);
+			 #else
+				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
+			 #endif
+			}
+			else if(type==SeqVecType){
+				this->svector=new SeqVec<doubletype>(m,M);
 			}
 			else _error_("Vector type: " << type << " not supported yet!");
@@ -111,6 +137,4 @@
 				#ifdef _HAVE_PETSC_
 				delete this->pvector;
-				#else
-				_error_("Petsc matrix format not usable, as Petsc has not been compiled!");
 				#endif
 			}
@@ -118,5 +142,4 @@
 				delete this->svector;
 			}
-			else _error_("Vector type: " << type << " not supported yet!");
 		}
 		/*}}}*/
@@ -171,5 +194,4 @@
 		void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -183,6 +205,4 @@
 			}
 			else _error_("Vector type: " << type << " not supported yet!");
-
-
 
 		}
@@ -207,5 +227,4 @@
 		/*FUNCTION GetValue{{{*/
 		void GetValue(doubletype* pvalue,int dof){
-
 
 			if(type==PetscVecType){
@@ -256,5 +275,4 @@
 		void GetLocalSize(int* pM){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -276,5 +294,4 @@
 			Vector* output=NULL;
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -298,5 +315,4 @@
 		void Set(doubletype value){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -316,5 +332,4 @@
 		void AXPY(Vector* X, doubletype a){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -334,5 +349,4 @@
 		void AYPX(Vector* X, doubletype a){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -346,5 +360,4 @@
 			}
 			else _error_("Vector type: " << type << " not supported yet!");
-
 
 		}
@@ -374,5 +387,4 @@
 		void Copy(Vector* to){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -386,5 +398,4 @@
 			}
 			else _error_("Vector type: " << type << " not supported yet!");
-
 
 		}
@@ -413,5 +424,4 @@
 		void Scale(doubletype scale_factor){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
@@ -451,5 +461,4 @@
 		void PointwiseDivide(Vector* x,Vector* y){
 
-
 			if(type==PetscVecType){
 				#ifdef _HAVE_PETSC_
Index: /issm/trunk/src/c/classes/matrix/matrixobjects.h
===================================================================
--- /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 13974)
+++ /issm/trunk/src/c/classes/matrix/matrixobjects.h	(revision 13975)
@@ -6,5 +6,4 @@
 #define ALL_MATRIX_OBJECTS_H_
 
-
 /*Numerics:*/
 #include "./ElementMatrix.h"
@@ -13,4 +12,3 @@
 #include "./Matrix.h"
 
-
 #endif
Index: sm/trunk/src/c/classes/objects.h
===================================================================
--- /issm/trunk/src/c/classes/objects.h	(revision 13974)
+++ 	(revision )
@@ -1,68 +1,0 @@
-/* \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 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/Constraint.h	(revision 13975)
@@ -4,5 +4,4 @@
  * It is derived from Object, so DataSets can contain them.
  */ 
-
 
 #ifndef _CONSTRAINT_H_
@@ -19,10 +18,9 @@
 
 	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 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.cpp	(revision 13975)
@@ -41,5 +41,5 @@
 }
 /*}}}*/
-		
+
 /*Object virtual functions definitions:*/
 /*FUNCTION SpcDynamic::Echo {{{*/
@@ -65,10 +65,4 @@
 /*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{{{*/
@@ -117,5 +111,5 @@
 /*FUNCTION SpcDynamic::GetNodeId {{{*/
 int   SpcDynamic::GetNodeId(){
-	
+
 	return nodeid;
 }
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h	(revision 13975)
@@ -33,5 +33,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp	(revision 13975)
@@ -40,5 +40,5 @@
 }
 /*}}}*/
-		
+
 /*Object virtual functions definitions:*/
 /*FUNCTION SpcStatic::Echo {{{*/
@@ -68,10 +68,4 @@
 /*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{{{*/
@@ -118,5 +112,5 @@
 /*FUNCTION SpcStatic::GetNodeId {{{*/
 int   SpcStatic::GetNodeId(){
-	
+
 	return nodeid;
 }
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h	(revision 13975)
@@ -32,5 +32,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp	(revision 13975)
@@ -54,5 +54,5 @@
 }
 /*}}}*/
-		
+
 /*Object virtual functions definitions:*/
 /*FUNCTION SpcTransient::Echo {{{*/
@@ -81,10 +81,4 @@
 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){
@@ -103,5 +97,5 @@
 /*FUNCTION SpcTransient::InAnalysis{{{*/
 bool SpcTransient::InAnalysis(int in_analysis_type){
-	
+
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
@@ -120,5 +114,5 @@
 	/*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
 
@@ -165,5 +159,5 @@
 /*FUNCTION SpcTransient::GetNodeId {{{*/
 int   SpcTransient::GetNodeId(){
-	
+
 	return nodeid;
 }
@@ -174,3 +168,2 @@
 }
 /*}}}*/
-
Index: /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h	(revision 13975)
@@ -34,5 +34,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Contour.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Contour.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Contour.h	(revision 13975)
@@ -22,18 +22,18 @@
 	public: 
 
-		int     id;
-		int	  nods;  //number of vertices in the contour
-		doubletype* x;
-		doubletype* y;
-		bool    closed; //is this contour closed?
+		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 {{{*/
+		/*FUNCTION Contour() {{{*/
 		Contour(){
-			this->id=0;
-			this->nods=0;
-			this->x=NULL;
-			this->y=NULL;
-			this->closed=false;
+			this->id     = 0;
+			this->nods   = 0;
+			this->x      = NULL;
+			this->y      = NULL;
+			this->closed = false;
 		}
 		/*}}}*/
@@ -41,7 +41,7 @@
 		Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){
 
-			this->id=pid;
-			this->nods=pnods;
-			this->closed=pclosed;
+			this->id     = pid;
+			this->nods   = pnods;
+			this->closed = pclosed;
 			if(nods){
 				this->x=xNew<doubletype>(nods);
@@ -52,5 +52,5 @@
 		}
 		/*}}}*/
-		/*FUNCTION Contour() default constructor {{{*/
+		/*FUNCTION ~Contour() {{{*/
 		~Contour(){
 			xDelete<doubletype>(this->x);
@@ -59,18 +59,14 @@
 		/*}}}*/
 
-
 		/*Object virtual function resolutoin: */
 		/*FUNCTION Echo(){{{*/
 		void Echo(void){
-
-			int i;
-
-			_printLine_("Contour: " << id);
-			_printLine_("   nods: " << nods);
-			_printLine_("   closed: " << (closed?"true":"false"));
+			_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]);
+				_printLine_("   x , y:");
+				for(int i=0;i<nods;i++){
+					_printLine_(i << ": " << x[i] << " | " << y[i]);
 				}
 			}
@@ -87,23 +83,12 @@
 		}
 		/*}}}*/
-		/*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); 
-
 		}
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/DependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/DependentObject.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/DependentObject.cpp	(revision 13975)
@@ -0,0 +1,104 @@
+/*!\file DependentObject.c
+ * \brief: implementation of the DependentObject object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+
+/*DependentObject constructors and destructor*/
+/*FUNCTION DependentObject::DependentObject(){{{*/
+DependentObject::DependentObject(){
+	this->name=NoneEnum;
+	this->type=0;
+	this->index=-1;
+}
+/*}}}*/
+/*FUNCTION DependentObject::DependentObject(int in_name, int in_type, int in_index){{{*/
+DependentObject::DependentObject(int in_name, int in_type,int in_index){
+
+	this->name=in_name;
+	this->type=in_type;
+	this->index=in_index;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an DependentObject of type " << in_type);
+	if(in_type==1)_error_("not implemented yet!");
+
+}
+/*}}}*/
+/*FUNCTION DependentObject::~DependentObject() {{{*/
+DependentObject::~DependentObject(){ //destructor
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DependentObject::Echo{{{*/
+void DependentObject::Echo(void){
+
+	_printLine_("DependentObject:");
+	_printLine_("   name: " << EnumToStringx(this->name));
+	if(this->type==0)
+		_printLine_("   type: scalar");
+	else if(this->type==1)
+		_printLine_("   type: vertex");
+	else
+		_error_(" unknown type: " << this->type);
+	if(this->index>=0) _printLine_("   index: " << this->index);
+}
+/*}}}*/
+/*FUNCTION DependentObject::DeepEcho{{{*/
+void DependentObject::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION DependentObject::Id{{{*/
+int    DependentObject::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DependentObject::ObjectEnum{{{*/
+int DependentObject::ObjectEnum(void){
+
+	return DependentObjectEnum;
+
+}
+/*}}}*/
+/*FUNCTION DependentObject::copy{{{*/
+Object* DependentObject::copy(void) { 
+	return new DependentObject(name,type,index);
+} /*}}}*/
+
+/*DependentObject methods: */
+/*FUNCTION DependentObject::NumDependents{{{*/
+int  DependentObject::NumDependents(void){
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		return 1;
+	}
+	else if(type==1){ /* vector:*/
+		_error_("not implemented yet!");
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
+/*FUNCTION DependentObject::Responsex{{{*/
+void  DependentObject::Responsex(IssmDouble* poutput_value,FemModel* femmodel){
+
+	if(this->name==MassFluxEnum){
+
+		/*to identify the mass flux that will be computed, we need the index of the profile: */
+		femmodel->parameters->SetParam(this->index,IndexEnum);
+	}
+
+	femmodel->Responsex(poutput_value,this->name,false,0);
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/DependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/objects/DependentObject.h	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/DependentObject.h	(revision 13975)
@@ -0,0 +1,47 @@
+/*!\file: DependentObject.h
+ * \brief prototype for DependentObject.h
+ */ 
+
+#ifndef _DEPENDENTOBJECT_H_
+#define  _DEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "./Object.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class Elements;
+class Nodes;
+class Vertices;
+class Loads;
+class Materials;
+class Parameters;
+class FemModel;
+
+class DependentObject: public Object{
+
+	public:
+
+		int name;
+		int type;  /*0: scalar, 1: vertex*/
+		int index;  /*0: scalar, 1: vertex*/
+
+		/*DependentObject constructors, destructors {{{*/
+		DependentObject();
+		DependentObject(int name, int type,int index);
+		~DependentObject();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy(void);
+		/*}}}*/
+
+		/*DependentObject methods: */
+		int  NumDependents(void);
+		void Responsex(IssmDouble* poutput_value,FemModel* femmodel);
+
+};
+#endif //ifndef _DEPENDENTOBJECT_H_
Index: /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp	(revision 13975)
@@ -58,10 +58,4 @@
 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){
@@ -116,5 +110,5 @@
 /*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
Index: /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h	(revision 13975)
@@ -3,5 +3,4 @@
  *  A boll result object is just derived from a BoolInput object, with additional time and step information.
  */
-
 
 #ifndef _BOOLELEMENTRESULT_H_
@@ -34,5 +33,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp	(revision 13975)
@@ -58,10 +58,4 @@
 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){
@@ -106,5 +100,5 @@
 /*FUNCTION DoubleElementResult::ProcessUnits{{{*/
 void DoubleElementResult::ProcessUnits(Parameters* parameters){
-	
+
 	this->value=UnitConversion(this->value,IuToExtEnum,this->enum_type);
 
@@ -118,5 +112,5 @@
 /*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
Index: /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h	(revision 13975)
@@ -3,5 +3,4 @@
  *  A IssmDouble result object is just derived from a DoubleInput object, with additional time and step information.
  */
-
 
 #ifndef _DOUBLEELEMENTRESULT_H_
@@ -34,5 +33,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief abstract class for ElementResult object
  */ 
-
 
 #ifndef _ELEMENTRESULT_H_
@@ -15,7 +14,6 @@
 
 	public: 
-		
+
 		virtual        ~ElementResult(){};
-		
 		virtual         ElementResult* SpawnTriaElementResult(int* indices)=0;
 		virtual IssmDouble  GetTime(void)=0;
Index: /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h	(revision 13975)
@@ -9,3 +9,2 @@
 
 #endif //ifndef _ELEMENTRESULTLOCAL_H_
-
Index: /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp	(revision 13975)
@@ -61,10 +61,4 @@
 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){
@@ -76,5 +70,5 @@
 /*FUNCTION PentaP1ElementResult::copy{{{*/
 Object* PentaP1ElementResult::copy() {
-	
+
 	return new PentaP1ElementResult(this->enum_type,this->values,this->step,this->time);
 
@@ -117,5 +111,5 @@
 /*FUNCTION PentaP1ElementResult::ProcessUnits{{{*/
 void PentaP1ElementResult::ProcessUnits(Parameters* parameters){
-	
+
 	UnitConversion(this->values,6,IuToExtEnum,this->enum_type);
 
@@ -129,5 +123,5 @@
 /*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
Index: /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h	(revision 13975)
@@ -3,5 +3,4 @@
  *  this object is just a PentaP1Input with additional time and step info.
  */
-
 
 #ifndef _PENTAP1ELEMENTRESULT_H_
@@ -33,5 +32,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp	(revision 13975)
@@ -49,5 +49,5 @@
 /*FUNCTION TriaP1ElementResult::DeepEcho{{{*/
 void TriaP1ElementResult::DeepEcho(void){
-		
+
 	_printLine_("TriaP1ElementResult:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -60,10 +60,4 @@
 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){
@@ -75,5 +69,5 @@
 /*FUNCTION TriaP1ElementResult::copy{{{*/
 Object* TriaP1ElementResult::copy() {
-	
+
 	return new TriaP1ElementResult(this->enum_type,this->values,this->step,this->time);
 
@@ -105,5 +99,5 @@
 /*FUNCTION TriaP1ElementResult::ProcessUnits{{{*/
 void TriaP1ElementResult::ProcessUnits(Parameters* parameters){
-	
+
 	UnitConversion(this->values,3,IuToExtEnum,this->enum_type);
 
@@ -117,5 +111,5 @@
 /*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
Index: /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for TriaP1ElementResult object
  */
-
 
 #ifndef _TRIAP1ELEMENTRESULT_H_
@@ -32,5 +31,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Elements/Element.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Element.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/Element.h	(revision 13975)
@@ -4,5 +4,4 @@
  * It is derived from Element, so DataSets can contain them.
  */ 
-
 
 #ifndef _ELEMENT_H_
@@ -25,9 +24,10 @@
 
 	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   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
 		virtual void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>*  Kfs,Vector<IssmDouble>* df)=0;
 		virtual void   CreatePVector(Vector<IssmDouble>* pf)=0;
@@ -35,4 +35,7 @@
 		virtual void   GetSolutionFromInputs(Vector<IssmDouble>* solution)=0;
 		virtual int    GetNodeIndex(Node* node)=0;
+		virtual int    GetNumberOfNodes(void)=0;
+		virtual void   GetNodesSidList(int* sidlist)=0;
+
 		virtual int    Sid()=0;
 		virtual bool   IsFloating()=0; 
@@ -43,5 +46,5 @@
 		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;
@@ -59,5 +62,5 @@
 		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;
Index: /issm/trunk/src/c/classes/objects/Elements/Penta.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Penta.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/Penta.cpp	(revision 13975)
@@ -82,5 +82,5 @@
 	this->inputs=new Inputs();
 	this->results=new Results();
-	
+
 	/*initialize pointers:*/
 	this->nodes=NULL;
@@ -180,10 +180,9 @@
 
 	/*Intermediaries */
-	int    count,ig;
+	int    count;
 	IssmDouble basalfriction[NUMVERTICES]={0,0,0,0,0,0};
 	IssmDouble alpha2,vx,vy;
 	Friction*  friction=NULL;
 	GaussPenta* gauss=NULL;
-
 
 	/* Basal friction can only be found at the base of an ice sheet: */
@@ -199,5 +198,4 @@
 	Input* vz_input=inputs->GetInput(VzEnum);                         _assert_(vz_input);
 
-
 	/*Build friction element, needed later: */
 	friction=new Friction("3d",inputs,matpar,DiagnosticHorizAnalysisEnum);
@@ -206,5 +204,5 @@
 	gauss=new GaussPenta(0,1,2,2);
 	count=0;
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -216,5 +214,5 @@
 		count++;
 	}
-	
+
 	/*Create PentaVertex input, which will hold the basal friction:*/
 	this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
@@ -228,21 +226,19 @@
 void  Penta::ComputeBasalStress(Vector<IssmDouble>* sigma_b){
 
-	int         i,j,ig;
+	int         i,j;
 	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;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  xyz_list_tria[3][3];
+	IssmDouble  rho_ice,gravity,stokesreconditioning;
+	IssmDouble  pressure,viscosity,Jdet2d;
+	IssmDouble  bed_normal[3];
+	IssmDouble  basalforce[3];
+	IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble  stresstensor[6]={0.0};
+	IssmDouble  sigma_xx,sigma_yy,sigma_zz;
+	IssmDouble  sigma_xy,sigma_xz,sigma_yz;
+	IssmDouble  surface=0,value=0;
 	GaussPenta* gauss;
 
@@ -257,5 +253,5 @@
 	/*retrieve some parameters: */
 	this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
-	
+
 	if(!IsOnBed()){
 		//put zero
@@ -280,5 +276,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -325,5 +321,4 @@
 void  Penta::ComputeStressTensor(){
 
-	int         iv;
 	IssmDouble      xyz_list[NUMVERTICES][3];
 	IssmDouble      pressure,viscosity;
@@ -364,5 +359,5 @@
 		sigma_yz[iv]=2*viscosity*epsilon[5];
 	}
-	
+
 	/*Add Stress tensor components into inputs*/
 	this->inputs->AddInput(new PentaP1Input(StressTensorxxEnum,&sigma_xx[0]));
@@ -381,5 +376,5 @@
 
 	int analysis_counter;
-	
+
 	/*go into parameters and get the analysis_counter: */
 	parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
@@ -421,5 +416,5 @@
 	_assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
 	/*}}}*/
-	
+
 	/*Skip if water element*/
 	if(IsOnWater()) return;
@@ -651,6 +646,4 @@
 void Penta::DeepEcho(void){
 
-	int i;
-	
 	_printLine_("Penta:");
 	_printLine_("   id: " << id);
@@ -672,6 +665,4 @@
 	_printLine_("neighboor sids: ");
 	_printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
-
-	return;
 }
 /*}}}*/
@@ -794,5 +785,5 @@
 void  Penta::GetDofList(int** pdoflist,int approximation_enum,int setenum){
 
-	int  i,j,count=0;
+	int  i,count=0;
 	int  numberofdofs=0;
 	int* doflist=NULL;
@@ -815,9 +806,17 @@
 }
 /*}}}*/
-/*FUNCTION Penta::GetDofList1 {{{*/
-void  Penta::GetDofList1(int* doflist){
+/*FUNCTION Penta::GetVertexPidList {{{*/
+void  Penta::GetVertexPidList(int* doflist){
 
 	int i;
-	for(i=0;i<6;i++) doflist[i]=nodes[i]->GetDofList1();
+	for(i=0;i<6;i++) doflist[i]=nodes[i]->GetVertexPid();
+
+}
+/*}}}*/
+/*FUNCTION Penta::GetVertexSidList{{{*/
+void  Penta::GetVertexSidList(int* sidlist){
+
+	int i;
+	for(i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetVertexSid();
 
 }
@@ -892,10 +891,32 @@
 }
 /*}}}*/
+/*FUNCTION Penta::GetNodesSidList{{{*/
+void Penta::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
+/*FUNCTION Penta::GetNumberOfNodes{{{*/
+int Penta::GetNumberOfNodes(void){
+
+	if(this->nodes==NULL) return 0;
+
+	switch(this->element_type){
+		case P1Enum:
+			return 6;
+		case P1DGEnum:
+			return 6;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
 /*FUNCTION Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
 void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
-
-	/*Intermediaries*/
-	IssmDouble     value[NUMVERTICES];
-	GaussPenta *gauss              = NULL;
 
 	/*Recover input*/
@@ -907,5 +928,5 @@
 
 	/* Start looping on the number of vertices: */
-	gauss=new GaussPenta();
+	GaussPenta *gauss=new GaussPenta();
 	for (int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
@@ -920,8 +941,4 @@
 void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
 
-	/*Intermediaries*/
-	IssmDouble     value[NUMVERTICES];
-	GaussPenta *gauss              = NULL;
-
 	/*Recover input*/
 	Input* input=inputs->GetInput(enumtype);
@@ -932,16 +949,14 @@
 	/* Start looping on the number of vertices: */
 	if (input){
-		gauss=new GaussPenta();
+		GaussPenta *gauss=new GaussPenta();
 		for (int iv=0;iv<NUMVERTICES;iv++){
 			gauss->GaussVertex(iv);
 			input->GetInputValue(&pvalue[iv],gauss);
 		}
+		delete gauss;
 	}
 	else{
 		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
 	}
-
-	/*clean-up*/
-	delete gauss;
 }
 /*}}}*/
@@ -995,12 +1010,4 @@
 	 *    = 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();
-
 }
 /*}}}*/
@@ -1135,5 +1142,5 @@
 void  Penta::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 
 	/*Get out if this is not an element input*/
@@ -1141,5 +1148,5 @@
 
 	/*Prepare index list*/
-	this->GetDofList1(&doflist1[0]);
+	this->GetVertexPidList(&vertexpidlist[0]);
 
 	/*Get input (either in element or material)*/
@@ -1148,5 +1155,5 @@
 
 	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
-	input->GetVectorFromInputs(vector,&doflist1[0]);
+	input->GetVectorFromInputs(vector,&vertexpidlist[0]);
 }
 /*}}}*/
@@ -1160,9 +1167,9 @@
 	}  
 	if(interp==P1Enum){
-		int doflist1[NUMVERTICES];
+		int vertexpidlist[NUMVERTICES];
 		int connectivity[NUMVERTICES];
-		this->GetSidList(&doflist1[0]);
+		this->GetVertexSidList(&vertexpidlist[0]);
 		this->GetConnectivityList(&connectivity[0]);
-		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
 	}
 	else if(interp==P0Enum){
@@ -1191,5 +1198,5 @@
 /*FUNCTION Penta::Sid {{{*/
 int    Penta::Sid(){
-	
+
 	return sid;
 
@@ -1251,5 +1258,5 @@
 	/*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)));
@@ -1269,5 +1276,5 @@
 
 	/*Intermediaries*/
-	int    i,j,t;
+	int    i,t;
 	int    penta_vertex_ids[6];
 	int    row;
@@ -1873,5 +1880,5 @@
 		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
 	}
-	
+
 	/*Free ressources:*/
 	xDelete<int>(doflist);
@@ -1897,5 +1904,5 @@
 	/*Add input to the element: */
 	this->inputs->AddInput(new PentaP1Input(enum_type,values));
-	
+
 	/*Free ressources:*/
 	xDelete<int>(doflist);
@@ -1937,5 +1944,5 @@
 		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
 	}
-	
+
 	/*Free ressources:*/
 	xDelete<int>(doflist);
@@ -1960,5 +1967,5 @@
 				/*Get values on the 6 vertices*/
 				for (int i=0;i<6;i++){
-					values[i]=vector[this->nodes[i]->GetVertexDof()];
+					values[i]=vector[this->nodes[i]->GetVertexPid()];
 				}
 
@@ -2162,4 +2169,5 @@
 	/*Recover info at the vertices: */
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
 	parameters->FindParam(&yts,ConstantsYtsEnum);
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -2170,5 +2178,5 @@
 	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++){
@@ -2211,5 +2219,5 @@
 		}
 	}
-	
+
    /*Add basal melting rate if element just ungrounded*/
 	if(!this->IsFloating() && elementonshelf==true){
@@ -2251,10 +2259,4 @@
 
 	return minlength;
-}
-/*}}}*/
-/*FUNCTION Penta::MyRank {{{*/
-int    Penta::MyRank(void){ 
-	extern int my_rank;
-	return my_rank; 
 }
 /*}}}*/
@@ -2299,5 +2301,5 @@
 	/*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.
@@ -2508,5 +2510,5 @@
 /*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: */
@@ -2607,4 +2609,55 @@
 }
 /*}}}*/
+/*FUNCTION Penta::SetwiseNodeConnectivity{{{*/
+void Penta::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<6;i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
 /*FUNCTION Penta::SpawnTria {{{*/
 Tria*  Penta::SpawnTria(int g0, int g1, int g2){
@@ -2663,4 +2716,6 @@
 	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
 	IssmDouble Hc[NUMVERTICES];					// elevation of transition between accumulation regime and ablation regime
+	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
+	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
 	IssmDouble smb_pos_max[NUMVERTICES];		// maximum SMB value in the accumulation regime
 	IssmDouble smb_pos_min[NUMVERTICES];		// minimum SMB value in the accumulation regime
@@ -2673,4 +2728,6 @@
 	/*Recover SmbGradients*/
 	GetInputListOnVertices(&Hc[0],SurfaceforcingsHcEnum);
+	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
+	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
 	GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
 	GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
@@ -2679,5 +2736,5 @@
 	GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
 	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
-	
+
    /*Recover surface elevatio at vertices: */
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -2687,17 +2744,18 @@
    rho_ice=matpar->GetRhoIce();
    rho_water=matpar->GetRhoFreshwater();
-			
+
    // loop over all vertices
-   for(i=0;i<NUMVERTICES;i++){
+ 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];}
+		  if(Href[i]>Hc[i]){smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);}
+		  if(Href[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];
+		  if(Href[i]>Hc[i]){smb[i]=a_neg[i]+b_neg[i]*s[i];}
+		  if(Href[i]<=Hc[i]){smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);}
 	  }
 	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
-	  
 	}  //end of the loop over the vertices
 	  /*Update inputs*/
@@ -2792,5 +2850,5 @@
 	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];
@@ -2974,5 +3032,5 @@
 		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){
@@ -2991,11 +3049,10 @@
 
 	/*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;
+	IssmDouble viscousheating[NUMVERTICES]={0,0,0,0,0,0};
+	IssmDouble thickness;
 	GaussPenta *gauss=NULL;
 
@@ -3014,5 +3071,5 @@
 	for (int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
-		
+
 		thickness_input->GetInputValue(&thickness,gauss);
 
@@ -3020,5 +3077,4 @@
 		material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
 		GetPhi(&phi, &epsilon[0], viscosity);
-		
 
 		viscousheating[iv]=phi*thickness;
@@ -3275,5 +3331,5 @@
 
 	if(IsOnWater() || !IsOnSurface()) return 0.;
-	
+
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
 
@@ -3287,8 +3343,8 @@
 	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;
@@ -3300,10 +3356,10 @@
 /*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;
@@ -3320,23 +3376,23 @@
 	/*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};
+	int        i,j,found=0;
+	IssmDouble Jdet,u,v,w,um,vm,wm;
+	IssmDouble h,hx,hy,hz,vx,vy,vz,vel;
+	IssmDouble gravity,rho_ice,rho_water;
+	IssmDouble epsvel=2.220446049250313e-16;
+	IssmDouble heatcapacity,thermalconductivity,dt;
+	IssmDouble pressure,enthalpy;
+	IssmDouble latentheat,kappa;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B_conduct[3][numdof];
+	IssmDouble B_advec[3][numdof];
+	IssmDouble Bprime_advec[3][numdof];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble D_scalar_conduct,D_scalar_advec;
+	IssmDouble D_scalar_trans,D_scalar_stab;
+	IssmDouble D[3][3];
+	IssmDouble K[3][3]={0.0};
 	Tria*      tria=NULL;
 	GaussPenta *gauss=NULL;
@@ -3367,5 +3423,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3476,12 +3532,12 @@
 
 	/*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;
+	int        i,j;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,heatcapacity;
+	IssmDouble Jdet2d,dt;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	IssmDouble D_scalar;
 	GaussPenta *gauss=NULL;
 
@@ -3502,11 +3558,11 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
-		
+
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
 		GetNodalFunctionsP1(&basis[0], gauss);
-				
+
 		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(rho_ice*heatcapacity);
 		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
@@ -3517,5 +3573,5 @@
 					&Ke->values[0],1);
 	}
-	
+
 	/*Clean up and return*/
 	delete gauss;
@@ -3537,10 +3593,10 @@
 /*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;
@@ -3557,20 +3613,20 @@
 	/*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};
+	int        i,j,found=0;
+	IssmDouble Jdet,u,v,w,um,vm,wm,vel;
+	IssmDouble h,hx,hy,hz,vx,vy,vz;
+	IssmDouble gravity,rho_ice,rho_water,kappa;
+	IssmDouble heatcapacity,thermalconductivity,dt;
+	IssmDouble tau_parameter,diameter;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B_conduct[3][numdof];
+	IssmDouble B_advec[3][numdof];
+	IssmDouble Bprime_advec[3][numdof];
+	IssmDouble L[numdof];
+	IssmDouble dbasis[3][6];
+	IssmDouble D_scalar_conduct,D_scalar_advec;
+	IssmDouble D_scalar_trans,D_scalar_stab;
+	IssmDouble D[3][3];
+	IssmDouble K[3][3]={0.0};
 	Tria*      tria=NULL;
 	GaussPenta *gauss=NULL;
@@ -3599,5 +3655,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3704,17 +3760,16 @@
 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;
+	int       i,j;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,heatcapacity;
+	IssmDouble Jdet2d,dt;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
+	IssmDouble D_scalar;
 	GaussPenta *gauss=NULL;
 
@@ -3735,11 +3790,11 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
-		
+
 		GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
 		GetNodalFunctionsP1(&basis[0], gauss);
-				
+
 		D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(heatcapacity*rho_ice);
 		if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
@@ -3750,5 +3805,5 @@
 					&Ke->values[0],1);
 	}
-	
+
 	/*Clean up and return*/
 	delete gauss;
@@ -3779,5 +3834,5 @@
 
 	/*Intermediaries*/
-	int    i,j,ig,found=0;
+	int    i,j,found=0;
 	int    friction_type,stabilization;
 	IssmDouble Jdet,phi,dt;
@@ -3822,5 +3877,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,3);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3875,12 +3930,12 @@
 
 	/*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];
+	int        i,j;
+	IssmDouble Jdet2d;
+	IssmDouble heatcapacity,h_pmp;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
 	GaussPenta* gauss=NULL;
 
@@ -3904,5 +3959,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3932,14 +3987,14 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        analysis_type;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble     Jdet2d,dt;
-	IssmDouble     rho_ice,heatcapacity,geothermalflux_value;
-	IssmDouble     basalfriction,alpha2,vx,vy;
-	IssmDouble     scalar,enthalpy,enthalpyup;
-	IssmDouble     pressure,pressureup;
-	IssmDouble     basis[NUMVERTICES];
+	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;
@@ -3972,5 +4027,5 @@
 	gauss=new GaussPenta(0,1,2,2);
 	gaussup=new GaussPenta(3,4,5,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4042,5 +4097,5 @@
 
 	/*Intermediaries*/
-	int    i,j,ig,found=0;
+	int    i,j,found=0;
 	int    friction_type,stabilization;
 	IssmDouble Jdet,phi,dt;
@@ -4078,5 +4133,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,3);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4129,12 +4184,12 @@
 
 	/*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];
+	int        i,j;
+	IssmDouble Jdet2d;
+	IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
+	IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
+	IssmDouble heatcapacity,t_pmp;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble basis[NUMVERTICES];
 	GaussPenta* gauss=NULL;
 
@@ -4158,5 +4213,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4186,13 +4241,13 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        analysis_type;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
-	IssmDouble     Jdet2d,dt;
-	IssmDouble     rho_ice,heatcapacity,geothermalflux_value;
-	IssmDouble     basalfriction,alpha2,vx,vy;
-	IssmDouble     basis[NUMVERTICES];
-	IssmDouble     scalar;
+	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;
@@ -4221,5 +4276,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4410,5 +4465,5 @@
 	GetInputListOnVertices(&pressure[0],PressureEnum);
 	Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
-	
+
 	this->inputs->GetInputValue(&converged,ConvergedEnum);
 	if(converged){
@@ -4419,5 +4474,5 @@
 			//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));
@@ -4463,5 +4518,5 @@
 void Penta::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 	Input* input=NULL;
 
@@ -4474,5 +4529,5 @@
 		input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
 	}
-		
+
 	else{
 		input=inputs->GetInput(enum_type);
@@ -4481,6 +4536,6 @@
 	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
-	GradientIndexing(&doflist1[0],control_index);
-	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
 
 }/*}}}*/
@@ -4507,5 +4562,5 @@
 void Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
 
-	int    doflist1[NUMVERTICES];
+	int    vertexpidlist[NUMVERTICES];
 	IssmDouble grad_list[NUMVERTICES];
 	Input* grad_input=NULL;
@@ -4524,6 +4579,6 @@
 	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]];
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
 	grad_input=new PentaP1Input(GradientEnum,grad_list);
 	((ControlInput*)input)->SetGradient(grad_input);
@@ -4587,19 +4642,16 @@
 ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
 
-	/*Constants*/
-	const int    numdof=NDOF2*NUMVERTICES;
-
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	bool       incomplete_adjoint;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     Jdet;
-	IssmDouble     eps1dotdphii,eps1dotdphij;
-	IssmDouble     eps2dotdphii,eps2dotdphij;
-	IssmDouble     mu_prime;
-	IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble     eps1[3],eps2[3];
-	IssmDouble     phi[NUMVERTICES];
-	IssmDouble     dphi[3][NUMVERTICES];
+	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;
 
@@ -4616,5 +4668,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4659,16 +4711,15 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	bool       incomplete_adjoint;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     Jdet;
-	IssmDouble     eps1dotdphii,eps1dotdphij;
-	IssmDouble     eps2dotdphii,eps2dotdphij;
-	IssmDouble     eps3dotdphii,eps3dotdphij;
-	IssmDouble     mu_prime;
-	IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble     eps1[3],eps2[3],eps3[3];
-	IssmDouble     phi[NUMVERTICES];
-	IssmDouble     dphi[3][NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble eps3dotdphii,eps3dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3],eps3[3];
+	IssmDouble dphi[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
@@ -4686,5 +4737,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4802,5 +4853,5 @@
 	/*get gradient indices*/
 	for(int i=0;i<NUMVERTICES;i++){
-		indexing[i]=num_controls*this->nodes[i]->GetVertexDof() + control_index;
+		indexing[i]=num_controls*this->nodes[i]->GetVertexPid() + control_index;
 	}
 
@@ -4913,17 +4964,17 @@
 void  Penta::GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index){
 
-	int        i,j,ig;
+	int        i,j;
 	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];
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
+	IssmDouble bed,thickness,Neff,drag;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble dk[NDOF3]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	IssmDouble grade_g_gaussian[NUMVERTICES];
+	IssmDouble basis[6];
 	Friction*  friction=NULL;
-	GaussPenta  *gauss=NULL;
+	GaussPenta *gauss=NULL;
 
 	/*Gradient is 0 if on shelf or not on bed*/
@@ -4932,5 +4983,5 @@
 	/*Retrieve all inputs and parameters*/
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[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];
@@ -4946,5 +4997,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4974,5 +5025,5 @@
 		}
 	}
-	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -4984,17 +5035,17 @@
 void  Penta::GradjDragStokes(Vector<IssmDouble>* gradient,int control_index){
 
-	int        i,j,ig;
+	int        i,j;
 	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];
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble bed,thickness,Neff;
+	IssmDouble lambda,mu,xi,Jdet,vx,vy,vz;
+	IssmDouble alpha_complement,drag;
+	IssmDouble surface_normal[3],bed_normal[3];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
+	IssmDouble dk[NDOF3]; 
+	IssmDouble basis[6];
+	IssmDouble grade_g[NUMVERTICES]={0.0};
+	IssmDouble grade_g_gaussian[NUMVERTICES];
 	Friction*  friction=NULL;
 	GaussPenta* gauss=NULL;
@@ -5007,5 +5058,5 @@
 	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);
+	GradientIndexing(&vertexpidlist[0],control_index);
 	Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
 	Input* vx_input      =inputs->GetInput(VxEnum);                  _assert_(vx_input);
@@ -5021,5 +5072,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,4);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5067,5 +5118,5 @@
 	}
 
-	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	delete friction;
@@ -5494,5 +5545,5 @@
 void  Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 
 	/*Get out if this is not an element input*/
@@ -5500,5 +5551,5 @@
 
 	/*Prepare index list*/
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Get input (either in element or material)*/
@@ -5511,5 +5562,5 @@
 	}
 
-	((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
 }
 /*}}}*/
@@ -5518,5 +5569,5 @@
 
 	IssmDouble  values[NUMVERTICES];
-	int     doflist1[NUMVERTICES];
+	int     vertexpidlist[NUMVERTICES];
 	Input  *input     = NULL;
 	Input  *new_input = NULL;
@@ -5526,12 +5577,11 @@
 
 	/*Prepare index list*/
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Get values on vertices*/
 	for (int i=0;i<NUMVERTICES;i++){
-		values[i]=vector[doflist1[i]];
+		values[i]=vector[vertexpidlist[i]];
 	}
 	new_input = new PentaP1Input(control_enum,values);
-
 
 	if(control_enum==MaterialsRheologyBbarEnum){
@@ -5554,5 +5604,5 @@
 /*FUNCTION Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
 void  Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-	
+
 	int i,j;
 
@@ -5569,5 +5619,5 @@
 			/*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!)
+				values[i]=vector[this->nodes[i]->GetVertexSid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
 			}
 
@@ -5581,5 +5631,5 @@
 					IssmDouble  surface[6];
 					IssmDouble  bed[6];
-					
+
 					/*retrieve inputs: */
 					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
@@ -5666,5 +5716,5 @@
 /*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;
@@ -5680,7 +5730,7 @@
 
 		case VertexEnum:
-			
+
 			/*Create transient input: */
-						
+
 			parameters->FindParam(&yts,ConstantsYtsEnum);
 
@@ -5689,5 +5739,5 @@
 				/*create input values: */
 				for(i=0;i<6;i++){
-					row=this->nodes[i]->GetSidList();
+					row=this->nodes[i]->GetVertexSid();
 					values[i]=(IssmDouble)matrix[ncols*row+t];
 				}
@@ -5753,10 +5803,10 @@
 /*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;
@@ -5775,15 +5825,15 @@
 
 	/*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.
+	int         i,j;
+	IssmDouble  Jdet;
+	IssmDouble  viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
+	IssmDouble  epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[3][numdofp];
+	IssmDouble  Bprime[3][numdofm];
+	IssmDouble  D[3][3]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble  D_scalar;
+	IssmDouble  Ke_gg[numdofp][numdofm]={0.0}; //local element stiffness matrix 
+	IssmDouble  Ke_gg_gaussian[numdofp][numdofm]; //stiffness matrix evaluated at the gaussian point.
 	GaussPenta *gauss=NULL;
 	GaussTria  *gauss_tria=NULL;
@@ -5820,5 +5870,5 @@
 	gauss=new GaussPenta(5,5);
 	gauss_tria=new GaussTria();
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5865,18 +5915,18 @@
 	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
+	int       i,j,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;
@@ -5913,5 +5963,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5934,5 +5984,5 @@
 		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,
@@ -5980,20 +6030,20 @@
 
 	/*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.
+	int         i,j;
+	IssmDouble Jdet;
+	IssmDouble viscosity,stokesreconditioning; //viscosity
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B[4][numdofs+3];
+	IssmDouble Bprime[4][numdofm];
+	IssmDouble B2[3][numdofm];
+	IssmDouble Bprime2[3][numdofs+3];
+	IssmDouble D[4][4]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble D2[3][3]={0.0};            // material matrix, simple scalar matrix.
+	IssmDouble D_scalar;
+	IssmDouble Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix 
+	IssmDouble Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix 
+	IssmDouble Ke_gg_gaussian[numdofs+3][numdofm]; //stiffness matrix evaluated at the gaussian point.
+	IssmDouble Ke_gg_gaussian2[numdofm][numdofs+3]; //stiffness matrix evaluated at the gaussian point.
 	GaussPenta *gauss=NULL;
 	GaussTria  *gauss_tria=NULL;
@@ -6029,5 +6079,5 @@
 	gauss=new GaussPenta(5,5);
 	gauss_tria=new GaussTria();
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6086,20 +6136,20 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        analysis_type,approximation;
-	IssmDouble     stokesreconditioning;
-	IssmDouble     viscosity,alpha2_gauss,Jdet2d;
-	IssmDouble	  bed_normal[3];
-	IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble	  xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble     LMacAyealStokes[8][numdof2dm];
-	IssmDouble     LprimeMacAyealStokes[8][numdof2d];
-	IssmDouble     DLMacAyealStokes[8][8]={0.0};
-	IssmDouble     LStokesMacAyeal[4][numdof2d];
-	IssmDouble     LprimeStokesMacAyeal[4][numdof2dm];
-	IssmDouble     DLStokesMacAyeal[4][4]={0.0};
-	IssmDouble     Ke_drag_gaussian[numdof2dm][numdof2d];
-	IssmDouble     Ke_drag_gaussian2[numdof2d][numdof2dm];
+	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;
@@ -6137,5 +6187,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6166,5 +6216,5 @@
 		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,
@@ -6387,5 +6437,5 @@
 
 	/*Intermediaries */
-	int         i,j,ig,approximation;
+	int         i,j,approximation;
 	IssmDouble  Jdet;
 	IssmDouble  viscosity , oldviscosity, newviscosity, viscosity_overshoot;
@@ -6423,5 +6473,5 @@
 	gauss=new GaussPenta(5,5);
 	gauss_tria=new GaussTria();
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6638,14 +6688,14 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        approximation;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     Jdet;
-	IssmDouble     viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
-	IssmDouble     epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
-	IssmDouble     D_scalar;
-	IssmDouble     D[5][5]={0.0};            // material matrix, simple scalar matrix.
-	IssmDouble     B[5][numdof];
-	IssmDouble     Bprime[5][numdof];
+	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;
@@ -6665,5 +6715,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6701,17 +6751,17 @@
 	/*Constants*/
 	const int numdof   = NDOF2*NUMVERTICES;
-	
+
 	/*Intermediaries */
-	int       i,j,ig;
+	int       i,j;
 	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;
+	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;
@@ -6736,5 +6786,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6752,8 +6802,8 @@
 			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,
@@ -6805,13 +6855,13 @@
 
 	/*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 
+	int        i,approximation;
+	IssmDouble Jdet,viscosity,stokesreconditioning;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
+	IssmDouble B[8][27];
+	IssmDouble B_prime[8][27];
+	IssmDouble D_scalar;
+	IssmDouble D[8][8]={0.0};
+	IssmDouble Ke_temp[27][27]={0.0}; //for the six nodes and the bubble 
 	GaussPenta *gauss=NULL;
 
@@ -6830,5 +6880,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6870,14 +6920,14 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        analysis_type,approximation;
-	IssmDouble     alpha2,Jdet2d;
-	IssmDouble     stokesreconditioning,viscosity;
-	IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble	  xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble     LStokes[2][numdof2d];
-	IssmDouble     DLStokes[2][2]={0.0};
-	IssmDouble     Ke_drag_gaussian[numdof2d][numdof2d];
+	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;
@@ -6902,5 +6952,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -6927,5 +6977,5 @@
 	/*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;
@@ -6936,5 +6986,5 @@
 /*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{*/
 ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
-	
+
 	/*compute all stiffness matrices for this element*/
 	ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
@@ -6956,10 +7006,9 @@
 
 	/*Intermediaries */
-	int         i,j,ig;
-	IssmDouble      Jdet;
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      B[NDOF1][NUMVERTICES];
-	IssmDouble      Bprime[NDOF1][NUMVERTICES];
-	IssmDouble      DL_scalar;
+	IssmDouble  Jdet;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  B[NDOF1][NUMVERTICES];
+	IssmDouble  Bprime[NDOF1][NUMVERTICES];
+	IssmDouble  DL_scalar;
 	GaussPenta  *gauss=NULL;
 
@@ -6972,5 +7021,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7002,10 +7051,10 @@
 
 	/*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];
+	int       i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble xyz_list_tria[NUMVERTICES2D][3];
+	IssmDouble surface_normal[3];
+	IssmDouble Jdet2d,DL_scalar;
+	IssmDouble basis[NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
@@ -7020,5 +7069,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(3,4,5,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7061,13 +7110,13 @@
 
 	/*Intermediaries */
-	int         i,j,ig;
+	int         i,j;
 	int         approximation;
-	IssmDouble      viscosity,Jdet;
-	IssmDouble      stokesreconditioning;
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble      dw[3];
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      basis[6]; //for the six nodes of the penta
-	IssmDouble      dbasis[3][6]; //for the six nodes of the penta
+	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;
 
@@ -7087,5 +7136,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7123,15 +7172,15 @@
 
 	/*Intermediaries*/
-	int         i,j,ig;
+	int         i,j;
 	int         approximation,analysis_type;
-	IssmDouble      Jdet,Jdet2d;
-	IssmDouble      stokesreconditioning;
-	IssmDouble	   bed_normal[3];
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble      viscosity, w, alpha2_gauss;
-	IssmDouble      dw[3];
-	IssmDouble	   xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      basis[6]; //for the six nodes of the penta
+	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;
@@ -7160,5 +7209,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7212,13 +7261,13 @@
 
 	/*Intermediaries */
-	int         i,j,ig;
+	int         i;
 	int         approximation;
-	IssmDouble      viscosity,Jdet;
-	IssmDouble      stokesreconditioning;
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble      dw[3];
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      basis[6]; //for the six nodes of the penta
-	IssmDouble      dbasis[3][6]; //for the six nodes of the penta
+	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;
 
@@ -7238,5 +7287,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7274,15 +7323,15 @@
 
 	/*Intermediaries*/
-	int         i,j,ig;
+	int         i,j;
 	int         approximation,analysis_type;
-	IssmDouble      Jdet,Jdet2d;
-	IssmDouble      stokesreconditioning;
-	IssmDouble	   bed_normal[3];
-	IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
-	IssmDouble      viscosity, w, alpha2_gauss;
-	IssmDouble      dw[3];
-	IssmDouble	   xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble      basis[6]; //for the six nodes of the penta
+	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;
@@ -7311,5 +7360,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7421,19 +7470,16 @@
 ElementVector* Penta::CreatePVectorDiagnosticHutter(void){
 
-	/*Constants*/
-	const int numdofs=NDOF2*NUMVERTICES;
-
 	/*Intermediaries*/
-	int          i,j,k,ig;
+	int          i,j;
 	int          node0,node1;
 	int          connectivity[2];
-	IssmDouble       Jdet;
-	IssmDouble       xyz_list[NUMVERTICES][3];
-	IssmDouble       xyz_list_segment[2][3];
-	IssmDouble       z_list[NUMVERTICES];
-	IssmDouble       z_segment[2],slope[2];
-	IssmDouble       slope2,constant_part;
-	IssmDouble       rho_ice,gravity,n,B;
-	IssmDouble       ub,vb,z_g,surface,thickness;
+	IssmDouble   Jdet;
+	IssmDouble   xyz_list[NUMVERTICES][3];
+	IssmDouble   xyz_list_segment[2][3];
+	IssmDouble   z_list[NUMVERTICES];
+	IssmDouble   slope[2];
+	IssmDouble   slope2,constant_part;
+	IssmDouble   rho_ice,gravity,n,B;
+	IssmDouble   ub,vb,z_g,surface,thickness;
 	GaussPenta*  gauss=NULL;
 
@@ -7468,5 +7514,5 @@
 		/*Loop on the Gauss points: */
 		gauss=new GaussPenta(node0,node1,3);
-		for(ig=gauss->begin();ig<gauss->end();ig++){
+		for(int ig=gauss->begin();ig<gauss->end();ig++){
 			gauss->GaussPoint(ig);
 
@@ -7541,10 +7587,10 @@
 
 	/*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];
+	int         i,j;
+	IssmDouble  Jdet;
+	IssmDouble  slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
+	IssmDouble  driving_stress_baseline,thickness;
+	IssmDouble  xyz_list[NUMVERTICES][3];
+	IssmDouble  basis[6];
 	GaussPenta  *gauss=NULL;
 
@@ -7559,5 +7605,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,3);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7603,19 +7649,18 @@
 
 	/*Intermediaries*/
-	int        i,j,ig;
+	int        i,j;
 	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];
+	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 
 	GaussPenta *gauss=NULL;
 
@@ -7636,5 +7681,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7680,14 +7725,14 @@
 
 	/*Intermediaries*/
-	int         i,j,ig;
+	int         i,j;
 	int         approximation,shelf_dampening;
-	IssmDouble      gravity,rho_water,bed,water_pressure;
-	IssmDouble      damper,normal_vel,vx,vy,vz,dt;
-	IssmDouble		xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble      xyz_list[NUMVERTICES][3];
-	IssmDouble		bed_normal[3];
-	IssmDouble      dz[3];
-	IssmDouble      basis[6]; //for the six nodes of the penta
-	IssmDouble      Jdet2d;
+	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;
 
@@ -7712,5 +7757,5 @@
 	/* 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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7765,5 +7810,4 @@
 
 	/*Intermediaries*/
-	int        i,ig;
 	int        approximation;
 	IssmDouble     Jdet;
@@ -7789,5 +7833,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(2,2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7806,5 +7850,5 @@
 		dvdy=dv[1];
 
-		for (i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
+		for(int i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
 	}
 
@@ -7817,17 +7861,16 @@
 ElementVector* Penta::CreatePVectorDiagnosticVertBase(void){
 
-
 	/*Constants*/
 	const int    numdof=NDOF1*NUMVERTICES;
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	int        approximation;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     xyz_list_tria[NUMVERTICES2D][3];
-	IssmDouble     Jdet2d;
-	IssmDouble     vx,vy,vz,dbdx,dbdy,basalmeltingvalue;
-	IssmDouble     slope[3];
-	IssmDouble     basis[NUMVERTICES];
+	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;
 
@@ -7852,5 +7895,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(0,1,2,2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -7940,14 +7983,13 @@
 
 	/*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];
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3];
+	IssmDouble dphi[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
@@ -7962,5 +8004,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -8005,15 +8047,14 @@
 
 	/*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];
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble eps3dotdphii,eps3dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
+	IssmDouble eps1[3],eps2[3],eps3[3];
+	IssmDouble dphi[3][NUMVERTICES];
 	GaussPenta *gauss=NULL;
 
@@ -8029,5 +8070,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussPenta(5,5);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -8416,5 +8457,5 @@
 		penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
 	}
-	
+
 	/*Free ressources:*/
 	xDelete<int>(doflist);
@@ -8688,5 +8729,5 @@
 /*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattyn {{{*/
 void  Penta::InputUpdateFromSolutionDiagnosticPattyn(IssmDouble* solution){
-	
+
 	const int    numdof=NDOF2*NUMVERTICES;
 
@@ -8856,5 +8897,5 @@
 /*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{*/
 void  Penta::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
-	
+
 	const int    numdof=NDOF2*NUMVERTICES;
 
@@ -8921,5 +8962,5 @@
 
 	const int numdof=NDOF1*NUMVERTICES;
-	
+
 	int      i;
 	int      approximation;
@@ -8938,5 +8979,4 @@
 	int*     doflist      = NULL;
 
-
 	/*Get the approximation and do nothing if the element in Stokes or None*/
 	inputs->GetInputValue(&approximation,ApproximationEnum);
@@ -9023,5 +9063,5 @@
 /*FUNCTION Penta::InputUpdateFromSolutionDiagnosticStokes {{{*/
 void  Penta::InputUpdateFromSolutionDiagnosticStokes(IssmDouble* solution){
-	
+
 	const int numdof=NDOF4*NUMVERTICES;
 
@@ -9063,5 +9103,5 @@
 	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: */
@@ -9133,3 +9173,2 @@
 /*}}}*/
 #endif
-
Index: /issm/trunk/src/c/classes/objects/Elements/Penta.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Penta.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/Penta.h	(revision 13975)
@@ -34,13 +34,13 @@
 		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
+		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
+		Parameters  *parameters;                  //pointer to solution parameters
 		Inputs      *inputs;
-		Results      *results;
+		Results     *results;
 
 		/*Penta constructors and destructor: {{{*/
@@ -50,10 +50,9 @@
 		/*}}}*/
 		/*Object virtual functions definitions: {{{*/
-		Object*   copy();
-		void	  DeepEcho();
-		void	  Echo();
-		int		  ObjectEnum();
-		int		  Id(); 
-		int		  MyRank();
+		Object *copy();
+		void    DeepEcho();
+		void    Echo();
+		int     ObjectEnum();
+		int     Id();
 		/*}}}*/
 		/*Update virtual functions definitions: {{{*/
@@ -81,4 +80,5 @@
 		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   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
 		void   CreatePVector(Vector<IssmDouble>* pf);
@@ -87,9 +87,11 @@
 		void   DeleteResults(void);
 		int    GetNodeIndex(Node* node);
+		void   GetNodesSidList(int* sidlist);
+		int    GetNumberOfNodes(void);
 		void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
 		IssmDouble GetZcoord(GaussPenta* gauss);
 		void   GetVectorFromInputs(Vector<IssmDouble>* vector,int name_enum);
 		void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int name_enum,int interp);
-		
+
 		int    Sid();
 		void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
@@ -100,5 +102,5 @@
 		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);
@@ -174,6 +176,6 @@
 		ElementVector* CreatePVectorSlope(void);
 		void	  GetDofList(int** pdoflist,int approximation_enum,int setenum);
-		void	  GetDofList1(int* doflist);
-		void    GetSidList(int* sidlist);
+		void	  GetVertexPidList(int* doflist);
+		void    GetVertexSidList(int* sidlist);
 		void    GetConnectivityList(int* connectivity);
 		int     GetElementType(void);
Index: /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp	(revision 13975)
@@ -49,5 +49,5 @@
 	/*intermediary: */
 	int matpar_id;
-	
+
 	/*retrieve parameters: */
 	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
@@ -70,5 +70,4 @@
 void PentaHook::SetHookNodes(int* node_ids,int analysis_counter){
 	this->hnodes[analysis_counter]= new Hook(node_ids,6);
-
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/objects/Elements/PentaHook.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaHook.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaHook.h	(revision 13975)
@@ -13,21 +13,19 @@
 
 	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
+		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 {{{*/
+		/*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 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaRef.cpp	(revision 13975)
@@ -699,5 +699,4 @@
 	IssmDouble l1l2l3[NUMNODESP1_2d];
 
-
 	/*Get l1l2l3 in actual coordinate system: */
 	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
@@ -812,5 +811,4 @@
 	IssmDouble l1l2l3[NUMNODESP1_2d];
 
-
 	/*Get l1l2l3 in actual coordinate system: */
 	l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
@@ -882,6 +880,4 @@
 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.*/
@@ -899,7 +895,7 @@
 	A3=gauss->coord3;
 
-	xi=A2-A1;
-	eta=SQRT3*A3;
-	zi=gauss->coord4;
+	xi  = A2-A1;
+	eta = SQRT3*A3;
+	zi  = gauss->coord4;
 
 	x1=*(xyz_list+3*0+0);
Index: /issm/trunk/src/c/classes/objects/Elements/PentaRef.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/PentaRef.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/PentaRef.h	(revision 13975)
@@ -4,15 +4,13 @@
  */ 
 
-
 #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);
Index: /issm/trunk/src/c/classes/objects/Elements/Tria.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Tria.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/Tria.cpp	(revision 13975)
@@ -42,6 +42,5 @@
 	:TriaRef(nummodels)
 	,TriaHook(nummodels,index+1,iomodel){
-		
-		int i;
+
 		/*id: */
 		this->id=tria_id;
@@ -127,12 +126,11 @@
 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];
+	bool       already = false;
+	int        i,j;
+	int        partition[NUMVERTICES];
+	int        offsetsid[NUMVERTICES];
+	int        offsetdof[NUMVERTICES];
+	IssmDouble area;
+	IssmDouble mean;
 
 	/*First, get the area: */
@@ -140,6 +138,6 @@
 
 	/*Figure out the average for this element: */
-	this->GetSidList(&offsetsid[0]);
-	this->GetDofList1(&offsetdof[0]);
+	this->GetVertexSidList(&offsetsid[0]);
+	this->GetVertexPidList(&offsetdof[0]);
 	mean=0;
 	for(i=0;i<NUMVERTICES;i++){
@@ -164,4 +162,55 @@
 }
 /*}}}*/
+/*FUNCTION Tria::SetwiseNodeConnectivity{{{*/
+void Tria::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<3;i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
 /*FUNCTION Tria::CreateKMatrix {{{*/
 void  Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df){
@@ -175,5 +224,5 @@
 	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
 	/*}}}*/
-	
+
 	/*Skip if water element*/
 	if(IsOnWater()) return;
@@ -231,5 +280,4 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
 	IssmDouble heatcapacity,latentheat;
 	IssmDouble Jdet,D_scalar;
@@ -248,5 +296,5 @@
 	/* Start looping on the number of gauss  (nodes on the bedrock) */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -290,18 +338,17 @@
 	/*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;
+	int        dim;
+	IssmDouble Jdettria,DL_scalar,dt,h;
+	IssmDouble vel,vx,vy,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble v_gauss[2]={0.0};
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble 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};
 
 	/*Initialize Element matrix*/
@@ -326,6 +373,6 @@
 
 	/* Start  looping on the number of gaussian points: */
-	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	GaussTria *gauss=new GaussTria(2);
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -409,13 +456,13 @@
 
 	/*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;
+	int        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;
 
@@ -440,5 +487,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -499,5 +546,5 @@
 
 		gauss->GaussPoint(ig);
-		
+
 		GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
 		D=gauss->weight*Jdet;
@@ -528,5 +575,5 @@
 	_assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
 	/*}}}*/
-	
+
 	/*Skip if water element*/
 	if(IsOnWater()) return;
@@ -597,9 +644,8 @@
 
 	/*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];
+	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;
 
@@ -618,5 +664,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -633,5 +679,5 @@
 		 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];
+		for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g-basal_melting_correction_g))*L[i];
 	}
 
@@ -648,9 +694,8 @@
 
 	/*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];
+	IssmDouble Jdettria,dt;
+	IssmDouble surface_mass_balance_g,basal_melting_g,thickness_g;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble L[NUMVERTICES];
 	GaussTria* gauss=NULL;
 
@@ -667,5 +712,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -678,5 +723,5 @@
 		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];
+		for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*L[i];
 	}
 
@@ -691,12 +736,12 @@
 	/*Constants*/
 	const int    numdof=NDOF1*NUMVERTICES;
-	
+
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i;
 	int        analysis_type;
-	IssmDouble     Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     slope[2];
-	IssmDouble     basis[3];
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble slope[2];
+	IssmDouble basis[3];
 	GaussTria* gauss=NULL;
 
@@ -714,8 +759,8 @@
 		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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -785,5 +830,4 @@
 void  Tria::ComputeStressTensor(){
 
-	int         iv;
 	IssmDouble      xyz_list[NUMVERTICES][3];
 	IssmDouble      pressure,viscosity;
@@ -820,5 +864,5 @@
 		sigma_xy[iv]=2*viscosity*epsilon[2];
 	}
-	
+
 	/*Add Stress tensor components into inputs*/
 	this->inputs->AddInput(new TriaP1Input(StressTensorxxEnum,&sigma_xx[0]));
@@ -835,5 +879,5 @@
 /*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;
@@ -894,5 +938,5 @@
 	_printLine_("neighboor sids: ");
 	_printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
-	
+
 	return;
 }
@@ -946,5 +990,5 @@
 	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++){
@@ -1027,5 +1071,5 @@
 	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;
@@ -1055,12 +1099,4 @@
 }
 /*}}}*/
-/*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(){
@@ -1090,10 +1126,32 @@
 }
 /*}}}*/
+/*FUNCTION Tria::GetNodesSidList{{{*/
+void Tria::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++){
+		sidlist[i]=nodes[i]->Sid();
+	}
+}
+/*}}}*/
+/*FUNCTION Tria::GetNumberOfNodes{{{*/
+int Tria::GetNumberOfNodes(void){
+
+	if(this->nodes==NULL) return 0;
+
+	switch(this->element_type){
+		case P1Enum:
+			return 3;
+		case P1DGEnum:
+			return 3;
+		default:
+			_error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
+	}
+}
+/*}}}*/
 /*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
 void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
-
-	/*Intermediaries*/
-	IssmDouble     value[NUMVERTICES];
-	GaussTria *gauss              = NULL;
 
 	/*Recover input*/
@@ -1105,5 +1163,5 @@
 
 	/* Start looping on the number of vertices: */
-	gauss=new GaussTria();
+	GaussTria* gauss=new GaussTria();
 	for (int iv=0;iv<NUMVERTICES;iv++){
 		gauss->GaussVertex(iv);
@@ -1118,6 +1176,4 @@
 void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
 
-	IssmDouble     value[NUMVERTICES];
-	GaussTria *gauss = NULL;
 	Input     *input = inputs->GetInput(enumtype);
 
@@ -1127,16 +1183,14 @@
 	/* Start looping on the number of vertices: */
 	if (input){
-		gauss=new GaussTria();
+		GaussTria* gauss=new GaussTria();
 		for (int iv=0;iv<NUMVERTICES;iv++){
 			gauss->GaussVertex(iv);
 			input->GetInputValue(&pvalue[iv],gauss);
 		}
+		delete gauss;
 	}
 	else{
 		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
 	}
-
-	/*clean-up*/
-	delete gauss;
 }
 /*}}}*/
@@ -1144,6 +1198,4 @@
 void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue,int index){
 
-	IssmDouble     value[NUMVERTICES];
-	GaussTria *gauss = NULL;
 	Input     *input = inputs->GetInput(enumtype);
 
@@ -1153,16 +1205,14 @@
 	/* Start looping on the number of vertices: */
 	if (input){
-		gauss=new GaussTria();
+		GaussTria* gauss=new GaussTria();
 		for (int iv=0;iv<NUMVERTICES;iv++){
 			gauss->GaussVertex(iv);
 			input->GetInputValue(&pvalue[iv],gauss,index);
 		}
+		delete gauss;
 	}
 	else{
 		for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
 	}
-
-	/*clean-up*/
-	delete gauss;
 }
 /*}}}*/
@@ -1180,7 +1230,15 @@
 }
 /*}}}*/
-/*FUNCTION Tria::GetSidList {{{*/
-void  Tria::GetSidList(int* sidlist){
-	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
+/*FUNCTION Tria::GetVertexPidList {{{*/
+void  Tria::GetVertexPidList(int* doflist){
+
+	int i;
+	for(i=0;i<3;i++) doflist[i]=nodes[i]->GetVertexPid();
+
+}
+/*}}}*/
+/*FUNCTION Tria::GetVertexSidList {{{*/
+void  Tria::GetVertexSidList(int* sidlist){
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetVertexSid();
 }
 /*}}}*/
@@ -1243,5 +1301,5 @@
 void  Tria::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 
 	/*Get out if this is not an element input*/
@@ -1249,5 +1307,5 @@
 
 	/*Prepare index list*/
-	this->GetDofList1(&doflist1[0]);
+	this->GetVertexPidList(&vertexpidlist[0]);
 
 	/*Get input (either in element or material)*/
@@ -1256,5 +1314,5 @@
 
 	/*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
-	input->GetVectorFromInputs(vector,&doflist1[0]);
+	input->GetVectorFromInputs(vector,&vertexpidlist[0]);
 }
 /*}}}*/
@@ -1268,9 +1326,9 @@
 	}
 	if(interp==P1Enum){
-		int doflist1[NUMVERTICES];
+		int vertexpidlist[NUMVERTICES];
 		int connectivity[NUMVERTICES];
-		this->GetSidList(&doflist1[0]);
+		this->GetVertexSidList(&vertexpidlist[0]);
 		this->GetConnectivityList(&connectivity[0]);
-		elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
+		elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
 	}
 	else if(interp==P0Enum){
@@ -1284,5 +1342,5 @@
 /*FUNCTION Tria::Id {{{*/
 int    Tria::Id(){
-	
+
 	return id;
 
@@ -1291,5 +1349,5 @@
 /*FUNCTION Tria::Sid {{{*/
 int    Tria::Sid(){
-	
+
 	return sid;
 
@@ -1392,10 +1450,11 @@
 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 (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;
@@ -1404,5 +1463,5 @@
 	 * 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){
@@ -1452,5 +1511,5 @@
 	IssmDouble yts;
 	int        num_cm_responses;
-   
+
 	/*Get parameters: */
 	iomodel->Constant(&yts,ConstantsYtsEnum); 
@@ -1687,5 +1746,5 @@
 			/*Get values on the 3 vertices*/
 			for (int i=0;i<3;i++){
-				values[i]=vector[this->nodes[i]->GetVertexDof()];
+				values[i]=vector[this->nodes[i]->GetVertexPid()];
 			}
 
@@ -1719,5 +1778,5 @@
 	/*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)));
@@ -1746,5 +1805,4 @@
 	int    numberofelements;
 	IssmDouble yts;
-
 
 	/*Fetch parameters: */
@@ -1861,5 +1919,5 @@
 /*FUNCTION Tria::IsOnBed {{{*/
 bool Tria::IsOnBed(){
-	
+
 	bool onbed;
 	inputs->GetInputValue(&onbed,MeshElementonbedEnum);
@@ -1967,5 +2025,5 @@
 void  Tria::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
 
-	int     i,migration_style,unground;
+	int     i,migration_style;
 	bool    elementonshelf = false;
 	IssmDouble  bed_hydro,yts,gl_melting_rate;
@@ -1976,4 +2034,5 @@
 	/*Recover info at the vertices: */
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
+	parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
 	parameters->FindParam(&yts,ConstantsYtsEnum);
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -1984,5 +2043,5 @@
 	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++){
@@ -2025,5 +2084,5 @@
 		}
 	}
-	
+
    /*Add basal melting rate if element just ungrounded*/
 	if(!this->IsFloating() && elementonshelf==true){
@@ -2038,10 +2097,4 @@
 	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; 
 }
 /*}}}*/
@@ -2087,5 +2140,5 @@
 	/*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.
 
@@ -2269,4 +2322,6 @@
 	IssmDouble b_neg[NUMVERTICES];				// Hs-SMB relation paremeter
 	IssmDouble Hc[NUMVERTICES];					// elevation of transition between accumulation regime and ablation regime
+	IssmDouble Href[NUMVERTICES];					// reference elevation from which deviations are used to calculate the SMB adjustment
+	IssmDouble Smbref[NUMVERTICES];				// reference SMB to which deviations are added
 	IssmDouble smb_pos_max[NUMVERTICES];		// maximum SMB value in the accumulation regime
 	IssmDouble smb_pos_min[NUMVERTICES];		// minimum SMB value in the accumulation regime
@@ -2279,4 +2334,6 @@
 	/*Recover SmbGradients*/
 	GetInputListOnVertices(&Hc[0],SurfaceforcingsHcEnum);
+	GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
+	GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
 	GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
 	GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
@@ -2285,5 +2342,5 @@
 	GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
 	GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
-	
+
    /*Recover surface elevatio at vertices: */
 	GetInputListOnVertices(&h[0],ThicknessEnum);
@@ -2293,17 +2350,26 @@
    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];}
+		  if(Href[i]>Hc[i]){smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);}
+		  if(Href[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];
+		  if(Href[i]>Hc[i]){smb[i]=a_neg[i]+b_neg[i]*s[i];}
+		  if(Href[i]<=Hc[i]){smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);}
 	  }
 	  smb[i]=smb[i]/rho_ice;      // SMB in m/y ice		
-	}  //end of the loop over the vertices
+  /*   printf("s %e \n",s[i]); 
+     printf("Hsref %e \n",Href[i]); 
+     printf("Hc %e \n",Hc[i]); 
+     printf("Smbref %e \n",Smbref[i]); 
+     printf("b_neg %e \n",b_neg[i]); 
+     printf("smb %e \n",smb[i]); 
+	  _error_("stop-in-code"); */
+		}  //end of the loop over the vertices
 	  /*Update inputs*/
 	  this->inputs->AddInput(new TriaP1Input(SurfaceforcingsMassBalanceEnum,&smb[0]));
@@ -2312,5 +2378,5 @@
 /*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;
@@ -2533,5 +2599,5 @@
 		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){
@@ -2574,13 +2640,12 @@
 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;
+	const int  numdofs=2;
+	int        dim;
+	IssmDouble mass_flux=0;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble normal[2];
+	IssmDouble length,rho_ice;
+	IssmDouble x1,y1,x2,y2,h1,h2;
+	IssmDouble vx1,vx2,vy1,vy2;
 	GaussTria* gauss_1=NULL;
 	GaussTria* gauss_2=NULL;
@@ -2842,8 +2907,8 @@
 	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;
@@ -2860,5 +2925,5 @@
 	ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyealFriction();
 	ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
-	
+
 	/*clean-up and return*/
 	delete Ke1;
@@ -2874,13 +2939,13 @@
 
 	/*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;
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble viscosity,newviscosity,oldviscosity;
+	IssmDouble viscosity_overshoot,thickness,Jdet;
+	IssmDouble epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
+	IssmDouble B[3][numdof];
+	IssmDouble Bprime[3][numdof];
+	IssmDouble D[3][3]   = {0.0};
+	IssmDouble D_scalar;
 	GaussTria *gauss = NULL;
 
@@ -2899,5 +2964,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -2938,15 +3003,15 @@
 
 	/*Intermediaries*/
-	int        i,j,ig;
+	int        i,j;
 	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];
+	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;
@@ -2969,5 +3034,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -2984,5 +3049,5 @@
 		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,
@@ -3028,11 +3093,11 @@
 
 	/*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];
+	int            i,j;
+	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;
 
@@ -3048,5 +3113,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3132,14 +3197,14 @@
 
 	/*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];
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet,thickness;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[3];/* epsilon=[exx,eyy,exy];*/
+	IssmDouble eps1[2],eps2[2];
+	IssmDouble phi[NUMVERTICES];
+	IssmDouble dphi[2][NUMVERTICES];
 	GaussTria *gauss=NULL;
 
@@ -3155,5 +3220,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3271,5 +3336,5 @@
 /*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{*/
 void  Tria::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
-	
+
 	const int numdof=NDOF2*NUMVERTICES;
 
@@ -3284,5 +3349,5 @@
 	IssmDouble    pressure[NUMVERTICES];
 	IssmDouble    thickness[NUMVERTICES];
-	
+
 	/*Get dof list: */
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
@@ -3334,7 +3399,7 @@
 /*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHutter {{{*/
 void  Tria::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
-	
+
 	const int numdof=NDOF2*NUMVERTICES;
-	
+
 	int       i;
 	int*      doflist=NULL;
@@ -3347,5 +3412,5 @@
 	IssmDouble    pressure[NUMVERTICES];
 	IssmDouble    thickness[NUMVERTICES];
-	
+
 	/*Get dof list: */
 	GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
@@ -3432,5 +3497,5 @@
 void Tria::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 	Input* input=NULL;
 
@@ -3444,6 +3509,6 @@
 	if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
 
-	GradientIndexing(&doflist1[0],control_index);
-	((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
+	GradientIndexing(&vertexpidlist[0],control_index);
+	((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
 
 }/*}}}*/
@@ -3467,5 +3532,5 @@
 void Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
 
-	int    doflist1[NUMVERTICES];
+	int    vertexpidlist[NUMVERTICES];
 	IssmDouble grad_list[NUMVERTICES];
 	Input* grad_input=NULL;
@@ -3481,6 +3546,6 @@
 	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]];
+	GradientIndexing(&vertexpidlist[0],control_index);
+	for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
 	grad_input=new TriaP1Input(GradientEnum,grad_list);
 
@@ -3555,16 +3620,16 @@
 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};
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
 	GaussTria  *gauss=NULL;
 
 	/*Retrieve all inputs we will be needing: */
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 	Input* rheologyb_input=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
 	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
@@ -3572,5 +3637,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3586,5 +3651,5 @@
 		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);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3595,16 +3660,16 @@
 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};
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
 	GaussTria  *gauss=NULL;
 
 	/*Retrieve all inputs we will be needing: */
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 	Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
 	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
@@ -3612,5 +3677,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3626,5 +3691,5 @@
 		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);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3636,12 +3701,12 @@
 
 	/*Intermediaries*/
-	int        i,ig;
+	int        i;
 	int        doflist[NUMVERTICES];
-	IssmDouble     vx,vy,lambda,mu,thickness,Jdet;
-	IssmDouble     viscosity_complement;
-	IssmDouble     dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2]; 
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basis[3],epsilon[3];
-	IssmDouble     grad[NUMVERTICES]={0.0};
+	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;
 
@@ -3660,5 +3725,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3693,12 +3758,12 @@
 
 	/*Intermediaries*/
-	int        i,ig;
+	int        i;
 	int        doflist[NUMVERTICES];
-	IssmDouble     vx,vy,lambda,mu,thickness,Jdet;
-	IssmDouble     viscosity_complement;
-	IssmDouble     dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dZ[NDOF2]; 
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basis[3],epsilon[3];
-	IssmDouble     grad[NUMVERTICES]={0.0};
+	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;
 
@@ -3717,5 +3782,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3749,16 +3814,16 @@
 void  Tria::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
 
-	int        i,ig;
+	int        i;
 	int        analysis_type;
-	int        doflist1[NUMVERTICES];
+	int        vertexpidlist[NUMVERTICES];
 	int        connectivity[NUMVERTICES];
-	IssmDouble     vx,vy,lambda,mu,alpha_complement,Jdet;
-	IssmDouble     bed,thickness,Neff,drag;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     dk[NDOF2]; 
-	IssmDouble     grade_g[NUMVERTICES]={0.0};
-	IssmDouble     grade_g_gaussian[NUMVERTICES];
-	IssmDouble     basis[3];
-	IssmDouble     epsilon[3]; /* epsilon=[exx,eyy,exy];*/
+	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;
@@ -3769,5 +3834,5 @@
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 	this->GetConnectivityList(&connectivity[0]);
 
@@ -3784,5 +3849,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3793,5 +3858,5 @@
 		/*Build alpha_complement_list: */
 		friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
-	
+
 		dragcoefficient_input->GetInputValue(&drag, gauss);
 		adjointx_input->GetInputValue(&lambda, gauss);
@@ -3805,5 +3870,5 @@
 			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++){
@@ -3827,5 +3892,5 @@
 	/*End Analytical gradient*/
 
-	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3837,11 +3902,11 @@
 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};
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble Jdet,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dbasis[NDOF2][NUMVERTICES];
+	IssmDouble dk[NDOF2]; 
+	IssmDouble grade_g[NUMVERTICES]={0.0};
 	GaussTria  *gauss=NULL;
 
@@ -3849,5 +3914,5 @@
 	if(IsFloating())return;
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 	Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
 	Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
@@ -3855,5 +3920,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3872,5 +3937,5 @@
 		}
 	}
-	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3882,14 +3947,14 @@
 
 	/*Intermediaries*/
-	int    doflist1[NUMVERTICES];
+	int    vertexpidlist[NUMVERTICES];
 	IssmDouble lambda[NUMVERTICES];
 	IssmDouble gradient_g[NUMVERTICES];
 
 	/*Compute Gradient*/
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[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);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,gradient_g,INS_VAL);
 }
 /*}}}*/
@@ -3898,16 +3963,16 @@
 
 	/*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};
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble thickness,Jdet;
+	IssmDouble basis[3];
+	IssmDouble Dlambda[2],dp[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble grade_g[NUMVERTICES] = {0.0};
 	GaussTria *gauss                = NULL;
 
 	/* Get node coordinates and dof list: */
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Retrieve all inputs we will be needing: */
@@ -3917,5 +3982,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3923,5 +3988,5 @@
 		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);
@@ -3931,5 +3996,5 @@
 	}
 
-	gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3941,16 +4006,16 @@
 
 	/*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};
+	int        i;
+	int        vertexpidlist[NUMVERTICES];
+	IssmDouble thickness,Jdet;
+	IssmDouble basis[3];
+	IssmDouble Dlambda[2],dp[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble grade_g[NUMVERTICES] = {0.0};
 	GaussTria *gauss                = NULL;
 
 	/* Get node coordinates and dof list: */
 	GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Retrieve all inputs we will be needing: */
@@ -3960,5 +4025,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -3973,5 +4038,5 @@
 		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);
+	gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
 
 	/*Clean up and return*/
@@ -3988,5 +4053,5 @@
 	/*get gradient indices*/
 	for(int i=0;i<NUMVERTICES;i++){
-		indexing[i]=num_controls*this->nodes[i]->GetVertexDof() + control_index;
+		indexing[i]=num_controls*this->nodes[i]->GetVertexPid() + control_index;
 	}
 
@@ -3997,10 +4062,9 @@
 
 	/* Intermediaries */
-	int        ig;
-	IssmDouble     Jelem = 0;
-	IssmDouble     weight;
-	IssmDouble     Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     dp[NDOF2];
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
 	GaussTria *gauss = NULL;
 
@@ -4017,5 +4081,5 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4040,11 +4104,8 @@
 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];
+	IssmDouble Jelem=0,S,Jdet;
+	IssmDouble misfit;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
 	GaussTria *gauss=NULL;
 
@@ -4065,5 +4126,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(3);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4101,14 +4162,11 @@
 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;
+	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;
 
@@ -4128,5 +4186,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4166,14 +4224,11 @@
 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];
+	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;
 
@@ -4190,8 +4245,8 @@
 	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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4232,11 +4287,8 @@
 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];
+	IssmDouble Jelem=0;
+	IssmDouble misfit,Jdet;
+	IssmDouble vx,vy,vxobs,vyobs,weight;
+	IssmDouble xyz_list[NUMVERTICES][3];
 	GaussTria *gauss=NULL;
 
@@ -4256,5 +4308,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4292,14 +4344,12 @@
 /*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];
+
+	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;
 
@@ -4319,5 +4369,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4358,10 +4408,9 @@
 
 	/* Intermediaries */
-	int        ig;
-	IssmDouble     Jelem = 0;
-	IssmDouble     weight;
-	IssmDouble     Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     dp[NDOF2];
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
 	GaussTria *gauss = NULL;
 
@@ -4378,5 +4427,5 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4402,5 +4451,4 @@
 
 	/* Intermediaries */
-	int         ig;
 	IssmDouble  Jelem = 0;
 	IssmDouble  weight;
@@ -4425,5 +4473,5 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4454,5 +4502,4 @@
 
 	/* Intermediaries */
-	int         ig;
 	IssmDouble  Jelem = 0;
 	IssmDouble  weight;
@@ -4477,5 +4524,5 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4506,11 +4553,10 @@
 
 	/*Intermediaries*/
-	int        i,ig;
-	IssmDouble     thickness,thicknessobs,weight;
-	IssmDouble     Jdet;
-	IssmDouble     Jelem = 0;
-	IssmDouble     xyz_list[NUMVERTICES][3];
+	IssmDouble thickness,thicknessobs,weight;
+	IssmDouble Jdet;
+	IssmDouble Jelem = 0;
+	IssmDouble xyz_list[NUMVERTICES][3];
 	GaussTria *gauss = NULL;
-	IssmDouble     dH[2];
+	IssmDouble dH[2];
 
 	/*If on water, return 0: */
@@ -4525,5 +4571,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4554,5 +4600,5 @@
 
 	/*Intermediaries */
-	int         i,ig,resp;
+	int         i,resp;
 	IssmDouble  Jdet;
 	IssmDouble  thickness,thicknessobs,weight;
@@ -4581,5 +4627,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4641,5 +4687,5 @@
 
 	/*Intermediaries */
-	int        i,resp,ig;
+	int        i,resp;
 	int       *responses=NULL;
 	int        num_responses;
@@ -4677,5 +4723,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -4823,5 +4869,5 @@
 
 	/*Intermediaries */
-	int        i,resp,ig;
+	int        i,resp;
 	int       *responses=NULL;
 	int        num_responses;
@@ -4859,5 +4905,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(4);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5006,10 +5052,9 @@
 
 	/* Intermediaries */
-	int        ig;
-	IssmDouble     Jelem = 0;
-	IssmDouble     weight;
-	IssmDouble     Jdet;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     dp[NDOF2];
+	IssmDouble Jelem = 0;
+	IssmDouble weight;
+	IssmDouble Jdet;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dp[NDOF2];
 	GaussTria *gauss = NULL;
 
@@ -5026,5 +5071,5 @@
 	/* Start looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5075,15 +5120,14 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
+	int        i,j;
 	bool       incomplete_adjoint;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     Jdet,thickness;
-	IssmDouble     eps1dotdphii,eps1dotdphij;
-	IssmDouble     eps2dotdphii,eps2dotdphij;
-	IssmDouble     mu_prime;
-	IssmDouble     epsilon[3];/* epsilon=[exx,eyy,exy];*/
-	IssmDouble     eps1[2],eps2[2];
-	IssmDouble     phi[NUMVERTICES];
-	IssmDouble     dphi[2][NUMVERTICES];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble Jdet,thickness;
+	IssmDouble eps1dotdphii,eps1dotdphij;
+	IssmDouble eps2dotdphii,eps2dotdphij;
+	IssmDouble mu_prime;
+	IssmDouble epsilon[3];/* epsilon=[exx,eyy,exy];*/
+	IssmDouble eps1[2],eps2[2];
+	IssmDouble dphi[2][NUMVERTICES];
 	GaussTria *gauss=NULL;
 
@@ -5101,5 +5145,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5205,5 +5249,5 @@
 void  Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
 
-	int doflist1[NUMVERTICES];
+	int vertexpidlist[NUMVERTICES];
 	Input *input=NULL;
 
@@ -5212,5 +5256,5 @@
 
 	/*Prepare index list*/
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Get input (either in element or material)*/
@@ -5227,5 +5271,5 @@
 	}
 
-	((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
+	((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
 }
 /*}}}*/
@@ -5234,5 +5278,5 @@
 
 	IssmDouble  values[NUMVERTICES];
-	int     doflist1[NUMVERTICES];
+	int     vertexpidlist[NUMVERTICES];
 	Input  *input     = NULL;
 	Input  *new_input = NULL;
@@ -5242,9 +5286,9 @@
 
 	/*Prepare index list*/
-	GradientIndexing(&doflist1[0],control_index);
+	GradientIndexing(&vertexpidlist[0],control_index);
 
 	/*Get values on vertices*/
 	for (int i=0;i<NUMVERTICES;i++){
-		values[i]=vector[doflist1[i]];
+		values[i]=vector[vertexpidlist[i]];
 	}
 	new_input = new TriaP1Input(control_enum,values);
@@ -5296,5 +5340,5 @@
 	/* compute VelocityFactor */
 	VelocityFactor= n_man*CR*CR*rho_water*g/mu_water;
-	
+
 	gauss=new GaussTria();
 	for (int iv=0;iv<NUMVERTICES;iv++){
@@ -5325,21 +5369,20 @@
 
 	/*Constants*/
-	const int    numdof=NDOF1*NUMVERTICES;
+	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};
+	IssmDouble diffusivity;
+	IssmDouble Jdettria,DL_scalar,dt,h;
+	IssmDouble vx,vy,vel,dvxdx,dvydy;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble v_gauss[2]={0.0};
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble 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;
 
@@ -5363,5 +5406,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5433,10 +5476,10 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
-	IssmDouble     Jdettria,dt;
-	IssmDouble     basal_melting_g;
-	IssmDouble     old_watercolumn_g;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basis[numdof];
+	int        i,j;
+	IssmDouble Jdettria,dt;
+	IssmDouble basal_melting_g;
+	IssmDouble old_watercolumn_g;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basis[numdof];
 	GaussTria* gauss=NULL;
 
@@ -5456,5 +5499,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5469,5 +5512,5 @@
 		else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
 	}
-		
+
 	/*Clean up and return*/
 	delete gauss;
@@ -5541,5 +5584,5 @@
 /*FUNCTION Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
 void  Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
-	
+
 	int i,j;
 
@@ -5556,5 +5599,5 @@
 			/*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!)
+				values[i]=vector[this->nodes[i]->GetVertexSid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
 			}
 
@@ -5567,5 +5610,5 @@
 					IssmDouble  surface[3];
 					IssmDouble  bed[3];
-					
+
 					/*retrieve inputs: */
 					GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
@@ -5640,5 +5683,5 @@
 /*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;
@@ -5654,7 +5697,7 @@
 
 		case VertexEnum:
-			
+
 			/*Create transient input: */
-						
+
 			parameters->FindParam(&yts,ConstantsYtsEnum);
 			for(t=0;t<ncols;t++){ //ncols is the number of times
@@ -5662,5 +5705,5 @@
 				/*create input values: */
 				for(i=0;i<3;i++){
-					row=this->nodes[i]->GetSidList();
+					row=this->nodes[i]->GetVertexSid();
 					values[i]=(IssmDouble)matrix[ncols*row+t];
 				}
@@ -5707,16 +5750,16 @@
 	/*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;
+	int        i,j,dim;
+	IssmDouble Jdettria,vx,vy,dvxdx,dvydy,vel,h;
+	IssmDouble dvx[2],dvy[2];
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble L[NUMVERTICES];
+	IssmDouble B[2][NUMVERTICES];
+	IssmDouble Bprime[2][NUMVERTICES];
+	IssmDouble K[2][2]                          = {0.0};
+	IssmDouble KDL[2][2]                        = {0.0};
+	IssmDouble DL[2][2]                         = {0.0};
+	IssmDouble DLprime[2][2]                    = {0.0};
+	IssmDouble DL_scalar;
 	GaussTria *gauss                            = NULL;
 
@@ -5742,5 +5785,5 @@
 	/*Start looping on the number of gaussian points:*/
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5816,11 +5859,11 @@
 
 	/*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;
+	int        i,j,dim;
+	IssmDouble vx,vy,Jdettria;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble B[2][NUMVERTICES];
+	IssmDouble Bprime[2][NUMVERTICES];
+	IssmDouble DL[2][2]={0.0};
+	IssmDouble DL_scalar;
 	GaussTria  *gauss=NULL;
 
@@ -5836,5 +5879,5 @@
 	/*Start looping on the number of gaussian points:*/
 	gauss=new GaussTria(2);
-	for (ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5882,10 +5925,10 @@
 	/*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];
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
+	IssmDouble L[NUMVERTICES];
 	GaussTria* gauss=NULL;
 
@@ -5898,8 +5941,8 @@
 	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++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
@@ -5927,8 +5970,8 @@
 
 	/*Intermediaries */
-	int        i,j,ig;
-	IssmDouble     xyz_list[NUMVERTICES][3];
-	IssmDouble     basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
-	IssmDouble     L[NUMVERTICES];
+	int        i,j;
+	IssmDouble xyz_list[NUMVERTICES][3];
+	IssmDouble basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
+	IssmDouble L[NUMVERTICES];
 	GaussTria* gauss=NULL;
 
@@ -5944,5 +5987,5 @@
 	/* Start  looping on the number of gaussian points: */
 	gauss=new GaussTria(2);
-	for(ig=gauss->begin();ig<gauss->end();ig++){
+	for(int ig=gauss->begin();ig<gauss->end();ig++){
 
 		gauss->GaussPoint(ig);
Index: /issm/trunk/src/c/classes/objects/Elements/Tria.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/Tria.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/Tria.h	(revision 13975)
@@ -29,15 +29,15 @@
 	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;
+		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 {{{*/
@@ -47,10 +47,9 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy();
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
@@ -77,4 +76,5 @@
 		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   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
 		void   CreatePVector(Vector<IssmDouble>* pf);
@@ -82,4 +82,6 @@
 		void   Delta18oParameterization(void);
 		int    GetNodeIndex(Node* node);
+		int    GetNumberOfNodes(void);
+		void   GetNodesSidList(int* sidlist);
 		int    Sid();
 		bool   IsOnBed();
@@ -137,5 +139,4 @@
 		#endif
 
-
 		#ifdef _HAVE_CONTROL_
 		IssmDouble DragCoefficientAbsGradient(bool process_units,int weight_index);
@@ -190,6 +191,6 @@
 		int            GetElementType(void);
 		void	         GetDofList(int** pdoflist,int approximation_enum,int setenum);
-		void	         GetDofList1(int* doflist);
-		void           GetSidList(int* sidlist);
+		void	         GetVertexPidList(int* doflist);
+		void           GetVertexSidList(int* sidlist);
 		void           GetConnectivityList(int* connectivity);
 		void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
@@ -203,5 +204,5 @@
 		void	         SetClone(int* minranks);
 		void	         SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
-		
+
 		#ifdef _HAVE_DIAGNOSTIC_
 		ElementMatrix* CreateKMatrixDiagnosticMacAyeal(void);
Index: /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp	(revision 13975)
@@ -50,5 +50,5 @@
 	/*retrieve parameters: */
 	iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
-	
+
 	this->numanalyses=in_numanalyses;
 	this->hnodes= new Hook*[in_numanalyses];
Index: /issm/trunk/src/c/classes/objects/Elements/TriaHook.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaHook.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaHook.h	(revision 13975)
@@ -17,5 +17,4 @@
 		Hook*  hmatpar; // 1 material parameter
 
-
 		/*FUNCTION constructors, destructors {{{*/
 		TriaHook();
@@ -27,5 +26,3 @@
 };
 
-
 #endif //ifndef _TRIAHOOK_H_
-
Index: /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp	(revision 13975)
@@ -319,5 +319,4 @@
 	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);
Index: /issm/trunk/src/c/classes/objects/Elements/TriaRef.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Elements/TriaRef.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Elements/TriaRef.h	(revision 13975)
@@ -3,5 +3,4 @@
  * strain rate generation, etc ...
  */ 
-
 
 #ifndef _TRIAREF_H_
@@ -11,10 +10,9 @@
 
 class TriaRef{
-	
 
 	public: 
 		int* element_type_list; //P1CG, P1DG, MINI, P2...
 		int  element_type;
-		
+
 		TriaRef();
 		TriaRef(const int nummodels);
Index: /issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief abstract class for ExternalResult object
  */ 
-
 
 #ifndef _EXTERNALRESULT_H_
@@ -23,5 +22,5 @@
 
 	public: 
-		
+
 		virtual        ~ExternalResult(){};
 		/*Virtual functions:{{{*/
Index: /issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h
===================================================================
--- /issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h	(revision 13975)
@@ -20,4 +20,5 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../classes/IssmComm.h"
 #include "./ExternalResult.h"
 /*}}}*/
@@ -34,5 +35,5 @@
 		int step;
 		IssmDouble time;
-	
+
 	public:
 		/*Diverse: must be in front, as it is used in what follows*/
@@ -99,8 +100,4 @@
 			return -1; 
 		} /*}}}*/
-		int MyRank(void){ /*{{{*/
-			extern int my_rank;
-			return my_rank; 
-		} /*}}}*/
 		int ObjectEnum(void){ /*{{{*/
 			_error_("template ObjectEnum not implemented for this ResultType\n");
@@ -112,10 +109,13 @@
 		/*GenericExternalResult management: */
 void WriteData(FILE* fid,bool io_gather){ /*{{{*/
-			
-	extern  int my_rank;
+
+	int     my_rank;
 	int     type;
 	int     size;
 	IssmPDouble  passiveDouble;
-	
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*return if now on cpu 0: */
 	if(my_rank)return;
@@ -205,7 +205,10 @@
 template <> inline void GenericExternalResult<char*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
 
-	extern  int my_rank;
+	int     my_rank;
 	int     type;
 	int     length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	/*return if now on cpu 0: */
@@ -235,5 +238,5 @@
 	M=in_M;
 	N=in_N;
-	
+
 	step=in_step;
 	time=in_time;
@@ -254,19 +257,17 @@
 } /*}}}*/
 template <> inline void GenericExternalResult<IssmPDouble*>::Echo(void){ /*{{{*/
-	
+
+	_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);
-
-} /*}}}*/
-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++){  
@@ -283,12 +284,14 @@
 } /*}}}*/
 template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
-	
-	extern  int my_rank;
+
+	int     my_rank;
 	int     length;
 	int     type;
 	int     rows,cols;
 	char   *name    = NULL;
-	extern  int my_rank;
 	IssmPDouble passiveDouble;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	if(io_gather){
Index: /issm/trunk/src/c/classes/objects/IndependentObject.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/IndependentObject.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/IndependentObject.cpp	(revision 13975)
@@ -0,0 +1,217 @@
+/*!\file IndependentObject.c
+ * \brief: implementation of the IndependentObject object
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./objects.h"
+#include "../../EnumDefinitions/EnumDefinitions.h"
+#include "../../shared/shared.h"
+#include "../../Container/Container.h"
+#include "../../include/include.h"
+#include "../IoModel.h"
+
+/*IndependentObject constructors and destructor*/
+/*FUNCTION IndependentObject::IndependentObject(){{{*/
+IndependentObject::IndependentObject(){
+	this->name=NoneEnum;
+	this->type=0;
+	this->numberofvertices=0;
+}
+/*}}}*/
+/*FUNCTION IndependentObject::IndependentObject(int in_name, int in_type,int in_numberofvertices){{{*/
+IndependentObject::IndependentObject(int in_name, int in_type,int in_numberofvertices){
+
+	this->numberofvertices=0;
+	this->name=in_name;
+	this->type=in_type;
+	if(in_type!=0 && in_type!=1)_error_("cannot create an IndependentObject of type " << in_type);
+	if(this->type==1)this->numberofvertices=in_numberofvertices;
+
+}
+/*}}}*/
+/*FUNCTION IndependentObject::~IndependentObject() {{{*/
+IndependentObject::~IndependentObject(){ //destructor
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION IndependentObject::Echo{{{*/
+void IndependentObject::Echo(void){
+
+	_printLine_("IndependentObject:");
+	_printLine_("   name: " << EnumToStringx(this->name));
+	if(this->type==0)
+		_printLine_("   type: scalar");
+	else if(this->type==1)
+		_printLine_("   type: vertex");
+	else
+		_error_(" unknown type: " << this->type);
+	_printLine_("   numberofvertices: " << this->numberofvertices);
+}
+/*}}}*/
+/*FUNCTION IndependentObject::DeepEcho{{{*/
+void IndependentObject::DeepEcho(void){
+	this->Echo();
+}
+/*}}}*/
+/*FUNCTION IndependentObject::Id{{{*/
+int    IndependentObject::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION IndependentObject::ObjectEnum{{{*/
+int IndependentObject::ObjectEnum(void){
+
+	return IndependentObjectEnum;
+
+}
+/*}}}*/
+/*FUNCTION IndependentObject::copy{{{*/
+Object* IndependentObject::copy(void) { 
+	return new IndependentObject(name,type,numberofvertices);
+} /*}}}*/
+
+/*IndependentObject methods: */
+/*FUNCTION IndependentObject::FetchIndependent{{{*/
+void IndependentObject::FetchIndependent(IoModel* iomodel){
+
+	int my_rank;
+	FILE* fid=NULL;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	#ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar: {{{*/
+
+		/*output: */
+		IssmPDouble  pscalar;
+		IssmDouble   scalar; //same as pscalar, except it's an ADOLC independent variable
+		IssmDouble*  scalar_slot=NULL;
+		int      code;
+
+		/*Set file pointer to beginning of the data: */
+		fid=iomodel->SetFilePointerToData(&code,NULL,name);
+
+		if(code!=3)_error_("expecting a IssmDouble for enum " << EnumToStringx(name));
+
+		/*We have to read a scalar from disk. First read the dimensions of the scalar, then the scalar: */
+		if(my_rank==0){
+			if(fread(&pscalar,sizeof(IssmPDouble),1,fid)!=1)_error_("could not read scalar ");
+		}
+
+		/*Now, before we even broadcast this to other nodes, declare the scalar  as an independent variable!: */
+		scalar<<=pscalar;
+
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
+		#endif
+
+		/*Ok, we are almost done. scalar is now an independent variable. We don't want this variable to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent variable inthe iomodel->data[name] data slot. Because this data slot holds double*, we allocate a sizeof(double)
+		 space for it: */
+		scalar_slot=xNew<IssmDouble>(1); *scalar_slot=scalar;
+
+		iomodel->data[name]=scalar_slot;
+		iomodel->independents[name]=true;
+
+	} /*}}}*/
+	else if(type==1){ /* vector: {{{*/
+
+		FILE* fid=NULL;
+		int M,N;
+		IssmPDouble* buffer=NULL; //a buffer to read the data from disk
+		IssmDouble* matrix=NULL; //our independent variable
+		int code=0;
+		int vector_type=0;
+
+		/*Set file pointer to beginning of the data: */
+		fid=iomodel->SetFilePointerToData(&code,&vector_type,name);
+		if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(name));
+
+		/*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
+		/*numberofelements: */
+		if(my_rank==0){  
+			if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm()); 
+		#endif
+
+		if(my_rank==0){  
+			if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
+		}
+		#ifdef _HAVE_MPI_
+		MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm()); 
+		#endif
+
+		/*Now allocate matrix: */
+		if(M*N){
+			buffer=xNew<IssmPDouble>(M*N);
+			matrix=xNew<IssmDouble>(M*N);
+
+			/*Read matrix on node 0, then broadcast: */
+			if(my_rank==0){  
+				if(fread(buffer,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
+
+				/*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!: */
+				for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
+			}
+			#ifdef _HAVE_MPI_
+			MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm()); 
+			#endif
+
+			xDelete<IssmPDouble>(buffer);
+		}
+		else _error_("cannot declare the independent variable " << EnumToStringx(name) <<  "if it's empty!");
+
+		/*Ok, we are almost done. Matrix is now a independent matrix. We don't want this matrix to be fetched again in the 
+		 *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this 
+		 independent matrix inthe iomodel->data[name] data slot: */
+		iomodel->data[name]=matrix;
+		iomodel->independents[name]=true;
+	}/*}}}*/
+	else _error_("should not have a type of " << type);
+
+	#endif
+}
+/*}}}*/
+/*FUNCTION IndependentObject::NumIndependents{{{*/
+int  IndependentObject::NumIndependents(void){
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		return 1;
+	}
+	else if(type==1){ /* vector:*/
+		return this->numberofvertices;
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
+/*FUNCTION IndependentObject::FillIndependents{{{*/
+void IndependentObject::FillIndependents(IssmDouble** data, IssmDouble* xp){
+
+	int i;
+
+	/*Branch according to the type of variable: */
+	if(type==0){ /*scalar:*/
+		xp[0]=*(data[name]);
+	}
+	else if(type==1){ /* vector:*/
+		IssmDouble* values=data[name];
+		for(i=0;i<this->numberofvertices;i++){
+			xp[i]=values[i];
+		}
+	}
+	else _error_("should not have a type of " << type);
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/IndependentObject.h
===================================================================
--- /issm/trunk/src/c/classes/objects/IndependentObject.h	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/IndependentObject.h	(revision 13975)
@@ -0,0 +1,41 @@
+/*!\file: IndependentObject.h
+ * \brief prototype for IndependentObject.h
+ */ 
+
+#ifndef _INDEPENDENTOBJECT_H_
+#define  _INDEPENDENTOBJECT_H_
+
+/*{{{*/
+#include "./Object.h"
+#include "../../shared/shared.h"
+/*}}}*/
+class IoModel;
+
+class IndependentObject: public Object{
+
+	public:
+
+		int name;
+		int type;  /*0: scalar, 1: vertex*/
+		int numberofvertices;
+
+		/*IndependentObject constructors, destructors {{{*/
+		IndependentObject();
+		IndependentObject(int name, int type, int numberofvertices);
+		~IndependentObject();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy(void);
+		/*}}}*/
+		/*IndependentObject methods: {{{*/
+		void FetchIndependent(IoModel* iomodel);
+		int  NumIndependents(void);
+		void FillIndependents(IssmDouble** data, IssmDouble* xp);
+		/*}}}*/
+
+};
+#endif //ifndef _INDEPENDENTOBJECT_H_
Index: /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp	(revision 13975)
@@ -23,6 +23,6 @@
 }
 /*}}}*/
-/*FUNCTION BoolInput::BoolInput(IssmDouble* values){{{*/
-BoolInput::BoolInput(int in_enum_type,IssmBool in_value){
+/*FUNCTION BoolInput::BoolInput(int in_enum_type,bool in_value){{{*/
+BoolInput::BoolInput(int in_enum_type,bool in_value){
 
 	enum_type=in_enum_type;
@@ -53,10 +53,4 @@
 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){
@@ -68,10 +62,10 @@
 /*FUNCTION BoolInput::copy{{{*/
 Object* BoolInput::copy() {
-	
+
 	return new BoolInput(this->enum_type,this->value);
 
 }
 /*}}}*/
-	
+
 /*BoolInput management*/
 /*FUNCTION BoolInput::InstanceEnum{{{*/
@@ -99,5 +93,5 @@
 /*FUNCTION BoolInput::SpawnResult{{{*/
 ElementResult* BoolInput::SpawnResult(int step, IssmDouble time){
-	
+
 	return new BoolElementResult(this->enum_type,this->value,step,time);
 
Index: /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/BoolInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _BOOLINPUT_H_
@@ -18,19 +17,18 @@
 	public:
 		/*just hold 3 values for 3 vertices: */
-		int    enum_type;
-		IssmBool value;
+		int  enum_type;
+		bool value;
 
 		/*BoolInput constructors, destructors: {{{*/
 		BoolInput();
-		BoolInput(int enum_type,IssmBool value);
+		BoolInput(int enum_type,bool value);
 		~BoolInput();
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy();
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
 		/*}}}*/
 		/*BoolInput management: {{{*/
Index: /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp	(revision 13975)
@@ -84,10 +84,4 @@
 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){
@@ -99,5 +93,5 @@
 /*FUNCTION ControlInput::copy{{{*/
 Object* ControlInput::copy() {
-	
+
 	ControlInput* output=NULL;
 
@@ -106,14 +100,14 @@
 	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();
+	if(values)      output->values      = dynamic_cast<Input*>(this->values->copy());
+	if(savedvalues) output->savedvalues = dynamic_cast<Input*>(this->savedvalues->copy());
+	if(minvalues)   output->minvalues   = dynamic_cast<Input*>(this->minvalues->copy());
+	if(maxvalues)   output->maxvalues   = dynamic_cast<Input*>(this->maxvalues->copy());
+	if(gradient)    output->gradient    = dynamic_cast<Input*>(this->gradient->copy());
 
 	return output;
 }
 /*}}}*/
-	
+
 /*ControlInput management*/
 /*FUNCTION ControlInput::InstanceEnum{{{*/
@@ -261,5 +255,5 @@
 
 	if(savedvalues) delete this->savedvalues;
-	this->savedvalues=(Input*)this->values->copy();
+	this->savedvalues=dynamic_cast<Input*>(this->values->copy());
 }/*}}}*/
 /*FUNCTION ControlInput::UpdateValue{{{*/
@@ -269,5 +263,5 @@
 
 	if(values) delete this->values;
-	this->values=(Input*)this->savedvalues->copy();
+	this->values=dynamic_cast<Input*>(this->savedvalues->copy());
 	this->values->AXPY(gradient,scalar);
 }/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/ControlInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _CONTROLINPUT_H_
@@ -34,5 +33,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp	(revision 13975)
@@ -55,10 +55,4 @@
 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){
@@ -70,5 +64,5 @@
 /*FUNCTION DatasetInput::copy{{{*/
 Object* DatasetInput::copy() {
-	
+
 	DatasetInput* output=NULL;
 
@@ -89,5 +83,5 @@
 	outinput=new DatasetInput();
 	outinput->enum_type=this->enum_type;
-	outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
+	outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(indices));
 
 	/*Assign output*/
@@ -95,5 +89,5 @@
 }
 /*}}}*/
-	
+
 /*DatasetInput management*/
 /*FUNCTION DatasetInput::InstanceEnum{{{*/
@@ -116,6 +110,6 @@
 	/*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* input=dynamic_cast<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 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/DatasetInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for datasetinput object
  */
-
 
 #ifndef _DATASETINPUT_H_
@@ -17,7 +16,6 @@
 
 	public:
-		int    enum_type;
-
-		Inputs*     inputs;
+		int     enum_type;
+		Inputs *inputs;
 
 		/*DatasetInput constructors, destructors: {{{*/
@@ -30,5 +28,4 @@
 		void  DeepEcho();
 		int   Id();
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp	(revision 13975)
@@ -53,10 +53,4 @@
 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){
@@ -68,10 +62,10 @@
 /*FUNCTION DoubleInput::copy{{{*/
 Object* DoubleInput::copy() {
-	
+
 	return new DoubleInput(this->enum_type,this->value);
 
 }
 /*}}}*/
-	
+
 /*DoubleInput management*/
 /*FUNCTION DoubleInput::InstanceEnum{{{*/
Index: /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _DOUBLEINPUT_H_
@@ -29,5 +28,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Inputs/Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/Input.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/Input.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief abstract class for Input object
  */ 
-
 
 #ifndef _INPUT_H_
@@ -19,5 +18,5 @@
 
 	public: 
-		
+
 		virtual        ~Input(){};
 
@@ -60,5 +59,5 @@
 		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;
Index: /issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp	(revision 13975)
@@ -48,10 +48,4 @@
 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){
@@ -63,5 +57,5 @@
 /*FUNCTION IntInput::copy{{{*/
 Object* IntInput::copy() {
-	
+
 	return new IntInput(this->enum_type,this->value);
 
@@ -98,5 +92,5 @@
 /*FUNCTION IntInput::SpawnResult{{{*/
 ElementResult* IntInput::SpawnResult(int step, IssmDouble time){
-	
+
 	_error_("not supported yet!");
 
Index: /issm/trunk/src/c/classes/objects/Inputs/IntInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/IntInput.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/IntInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _INTINPUT_H_
@@ -30,5 +29,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp	(revision 13975)
@@ -64,10 +64,4 @@
 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){
@@ -77,9 +71,9 @@
 }
 /*}}}*/
-	
+
 /*PentaP1Input management*/
 /*FUNCTION PentaP1Input::copy{{{*/
 Object* PentaP1Input::copy() {
-	
+
 	return new PentaP1Input(this->enum_type,this->values);
 
@@ -363,5 +357,5 @@
 /*FUNCTION PentaP1Input::ConstrainMin{{{*/
 void PentaP1Input::ConstrainMin(IssmDouble minimum){
-	
+
 	int i;
 	const int numnodes=6;
@@ -431,5 +425,5 @@
 /*FUNCTION PentaP1Input::Scale{{{*/
 void PentaP1Input::Scale(IssmDouble scale_factor){
-	
+
 	int i;
 	const int numnodes=6;
@@ -470,5 +464,5 @@
 	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;
@@ -522,9 +516,7 @@
 
 	/*Intermediaries*/
-	int               i;
-	PentaP1Input *xinputB     = NULL;
-	int               B_numvalues;
-	const int         numnodes    = 6;
-	IssmDouble            AdotBvalues[numnodes];
+	PentaP1Input *xinputB  = NULL;
+	const int     numnodes = 6;
+	IssmDouble    AdotBvalues[numnodes];
 
 	/*Check that inputB is of the same type*/
@@ -533,5 +525,5 @@
 
 	/*Create point wise sum*/
-	for(i=0;i<numnodes;i++){
+	for(int i=0;i<numnodes;i++){
 		_assert_(xinputB->values[i]!=0);
 		AdotBvalues[i]=this->values[i]/xinputB->values[i];
@@ -555,5 +547,4 @@
 	int               i;
 	PentaP1Input *xinputB     = NULL;
-	int               B_numvalues;
 	const int         numnodes    = 6;
 	IssmDouble            minvalues[numnodes];
@@ -586,5 +577,4 @@
 	int               i;
 	PentaP1Input *xinputB     = NULL;
-	int               B_numvalues;
 	const int         numnodes    = 6;
 	IssmDouble            maxvalues[numnodes];
Index: /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for PentaP1Input object
  */
-
 
 #ifndef _PENTAP1INPUT_H_
@@ -18,5 +17,5 @@
 	public:
 		/*just hold 6 values for 6 vertices: */
-		int    enum_type;
+		int        enum_type;
 		IssmDouble values[6];
 
@@ -27,10 +26,9 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy();
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
 		/*}}}*/
 		/*PentaP1Input management: {{{*/
Index: /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp	(revision 13975)
@@ -79,10 +79,4 @@
 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){
@@ -109,5 +103,5 @@
 }
 /*}}}*/
-	
+
 /*TransientInput management*/
 /*FUNCTION TransientInput::InstanceEnum{{{*/
@@ -222,5 +216,5 @@
 	/*Retrieve interpolated values for this time step: */
 	Input* input=GetTimeInput(time);
-		   
+
 	/*Call input function*/
 	input->GetInputDerivativeValue(p,xyz_list,gauss);
@@ -237,5 +231,5 @@
 /*FUNCTION TransientInput::GetInputAverage{{{*/
 void TransientInput::GetInputAverage(IssmDouble* pvalue){
-	
+
 	IssmDouble time;
 
@@ -248,5 +242,5 @@
 	/*Call input function*/
 	input->GetInputAverage(pvalue);
-			   
+
 	delete input;
 
@@ -302,8 +296,8 @@
    /*Retrieve interpolated values for this time step: */
 	Input* input=GetTimeInput(time);
-		   
+
 	/*Call input function*/
 	input->SquareMin(psquaremin,process_units,parameters);
-			   
+
 	delete input;
 
@@ -324,5 +318,5 @@
 	/*Call input function*/
 	infnorm=input->InfinityNorm();
-			   
+
 	/*Clean-up and return*/
 	delete input;
@@ -341,8 +335,8 @@
    /*Retrieve interpolated values for this time step: */
 	Input* input=GetTimeInput(time);
-		   
+
 	/*Call input function*/
 	max=input->Max();
-			   
+
 	delete input;
 
@@ -406,5 +400,5 @@
 	/*Call input function*/
 	minabs=input->MinAbs();
-			   
+
 	/*Clean-up and return*/
 	delete input;
@@ -422,8 +416,8 @@
 	/*Retrieve interpolated values for this time step: */
 	Input* input=GetTimeInput(time);
-		   
+
 	/*Call input function*/
 	input->GetVectorFromInputs(vector,doflist);
-			   
+
 	delete input;
 
@@ -432,55 +426,42 @@
 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 
+	IssmDouble deltat;
+	IssmDouble alpha1,alpha2;
+	int        found;
+	int        offset;
+
+	Input *input  = NULL;
+	Input *input1 = NULL;
+	Input *input2 = NULL;
+
+	/*go through the timesteps, and figure out which interval we 
 	 *fall within. Then interpolate the values on this interval: */
-	if(intime<this->timesteps[0]){
+	found=binary_search(&offset,intime,this->timesteps,this->numtimesteps);
+	if(!found) _error_("Input not found (is TransientInput sorted ?)");
+
+	if (offset==-1){
 		/*get values for the first time: */
+		_assert_(intime<this->timesteps[0]);
 		input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
-		found=true;
-	}
-	else if(intime>this->timesteps[this->numtimesteps-1]){
+	}
+	else if(offset==(this->numtimesteps-1)){
 		/*get values for the last time: */
-		input=(Input*)((Input*)this->inputs->GetObjectByOffset(numtimesteps-1))->copy();
-		found=true;
+		_assert_(intime>=this->timesteps[offset]);
+		input=(Input*)((Input*)this->inputs->GetObjectByOffset(offset))->copy();
 	}
 	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!");
+		/*get values between two times [offset:offset+1[, Interpolate linearly*/
+		_assert_(intime>=this->timesteps[offset] && intime<this->timesteps[offset+1]);
+		deltat=this->timesteps[offset+1]-this->timesteps[offset];
+		alpha2=(intime-this->timesteps[offset])/deltat;
+		alpha1=(1.0-alpha2);
+
+		input1=(Input*)this->inputs->GetObjectByOffset(offset); 
+		input2=(Input*)this->inputs->GetObjectByOffset(offset+1);
+
+		input=(Input*)input1->copy();
+		input->Scale(alpha1);
+		input->AXPY(input2,alpha2);
+	}
 
 	/*Assign output pointer*/
Index: /issm/trunk/src/c/classes/objects/Inputs/TransientInput.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TransientInput.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/TransientInput.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for transientinput object
  */
-
 
 #ifndef _TRANSIENTINPUT_H_
@@ -17,9 +16,9 @@
 
 	public:
-		int     enum_type;
-		int     numtimesteps;
-		Inputs* inputs;
-		IssmDouble* timesteps;
-		Parameters* parameters; //to find current time.
+		int         enum_type;
+		int         numtimesteps;
+		Inputs     *inputs;
+		IssmDouble *timesteps;
+		Parameters *parameters;     //to find current time.
 
 		/*TransientInput constructors, destructors: {{{*/
@@ -33,5 +32,4 @@
 		void  DeepEcho();
 		int   Id();
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp	(revision 13975)
@@ -64,10 +64,4 @@
 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){
@@ -79,10 +73,10 @@
 /*FUNCTION TriaP1Input::copy{{{*/
 Object* TriaP1Input::copy() {
-	
+
 	return new TriaP1Input(this->enum_type,this->values);
 
 }
 /*}}}*/
-	
+
 /*TriaP1Input management*/
 /*FUNCTION TriaP1Input::InstanceEnum{{{*/
@@ -214,5 +208,5 @@
 /*FUNCTION TriaP1Input::ContrainMin{{{*/
 void TriaP1Input::ConstrainMin(IssmDouble minimum){
-	
+
 	int i;
 	const int numnodes=3;
@@ -282,5 +276,5 @@
 /*FUNCTION TriaP1Input::Scale{{{*/
 void TriaP1Input::Scale(IssmDouble scale_factor){
-	
+
 	int i;
 	const int numnodes=3;
@@ -333,5 +327,5 @@
 	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;
@@ -361,9 +355,8 @@
 
 	/*Intermediaries*/
-	int               i;
-	TriaP1Input *xinputB     = NULL;
-	int               B_numvalues;
-	const int         numnodes    = 3;
-	IssmDouble            minvalues[numnodes];
+	int          i;
+	TriaP1Input *xinputB  = NULL;
+	const int    numnodes = 3;
+	IssmDouble   minvalues[numnodes];
 
 	/*Check that inputB is of the same type*/
@@ -394,5 +387,4 @@
 	int               i;
 	TriaP1Input *xinputB     = NULL;
-	int               B_numvalues;
 	const int         numnodes    = 3;
 	IssmDouble            maxvalues[numnodes];
Index: /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for TriaP1Input object
  */
-
 
 #ifndef _TRIAP1INPUT_H_
@@ -18,5 +17,5 @@
 	public:
 		/*just hold 3 values for 3 vertices: */
-		int    enum_type;
+		int        enum_type;
 		IssmDouble values[3];
 
@@ -27,10 +26,9 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy();
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
 		/*}}}*/
 		/*TriaP1Input management: {{{*/
Index: /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp	(revision 13975)
@@ -545,5 +545,5 @@
 					  FILE* fid){
 
-	int     i=-1,j;
+	int     i=-1;
 	char*   kstr;
 	char*   ktok;
Index: /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h	(revision 13975)
@@ -55,3 +55,2 @@
 
 #endif  /* _KMLFILEREADUTILS_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Attribute.h	(revision 13975)
@@ -31,8 +31,4 @@
 		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.");};
@@ -48,3 +44,2 @@
 };
 #endif  /* _KML_ATTRIBUTE_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h	(revision 13975)
@@ -36,7 +36,4 @@
 		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.");};
@@ -46,3 +43,2 @@
 };
 #endif  /* _KML_COLORSTYLE_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Comment.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Comment.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Comment.h	(revision 13975)
@@ -31,8 +31,4 @@
 		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.");};
@@ -48,3 +44,2 @@
 };
 #endif  /* _KML_COMMENT_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Container.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Container.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Container.h	(revision 13975)
@@ -34,8 +34,4 @@
 		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.");};
@@ -44,3 +40,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Document.cpp	(revision 13975)
@@ -125,3 +125,2 @@
 }
 /*}}}*/
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Document.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Document.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Document.h	(revision 13975)
@@ -31,8 +31,4 @@
 		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.");};
@@ -41,3 +37,2 @@
 };
 #endif  /* _KML_DOCUMENT_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Feature.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Feature.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Feature.h	(revision 13975)
@@ -45,8 +45,4 @@
 		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.");};
@@ -55,3 +51,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_File.cpp	(revision 13975)
@@ -90,5 +90,4 @@
 	int          ncom=0;
 	char**       pcom=NULL;
-	KML_Object*  kobj;
 
 /*  get object attributes and check for solo tag  */
Index: /issm/trunk/src/c/classes/objects/KML/KML_File.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_File.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_File.h	(revision 13975)
@@ -32,8 +32,4 @@
 		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.");};
@@ -42,3 +38,2 @@
 };
 #endif  /* _KML_FILE_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Folder.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Folder.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Folder.h	(revision 13975)
@@ -31,8 +31,4 @@
 		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.");};
@@ -41,3 +37,2 @@
 };
 #endif  /* _KML_FOLDER_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Geometry.h	(revision 13975)
@@ -30,8 +30,4 @@
 		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.");};
@@ -40,3 +36,2 @@
 };
 #endif  /* _KML_GEOMETRY_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h	(revision 13975)
@@ -37,8 +37,4 @@
 		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.");};
@@ -47,3 +43,2 @@
 };
 #endif  /* _KML_GROUNDOVERLAY_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Icon.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Icon.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Icon.h	(revision 13975)
@@ -45,8 +45,4 @@
 		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.");};
@@ -55,3 +51,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.cpp	(revision 13975)
@@ -43,5 +43,4 @@
 /*FUNCTION KML_LatLonBox::Echo {{{*/
 void  KML_LatLonBox::Echo(){
-
 
 	_printLine_("KML_LatLonBox:");
Index: /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h	(revision 13975)
@@ -36,8 +36,4 @@
 		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.");};
@@ -46,3 +42,2 @@
 };
 #endif  /* _KML_LATLONBOX_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineString.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineString.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineString.h	(revision 13975)
@@ -39,8 +39,4 @@
 		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.");};
@@ -49,3 +45,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.cpp	(revision 13975)
@@ -63,5 +63,4 @@
 void  KML_LineStyle::DeepEcho(const char* indent){
 
-	int   i;
 	bool  flag=true;
 
Index: /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h	(revision 13975)
@@ -32,8 +32,4 @@
 		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.");};
@@ -42,3 +38,2 @@
 };
 #endif  /* _KML_LINESTYLE_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h	(revision 13975)
@@ -39,8 +39,4 @@
 		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.");};
@@ -49,3 +45,2 @@
 };
 #endif  /* _KML_LINEARRING_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h	(revision 13975)
@@ -35,8 +35,4 @@
 		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.");};
@@ -45,3 +41,2 @@
 };
 #endif  /* _KML_MULTIGEOMETRY_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Object.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Object.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Object.h	(revision 13975)
@@ -32,8 +32,4 @@
 		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.");};
@@ -54,3 +50,2 @@
 };
 #endif  /* _KML_OBJECT_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Overlay.h	(revision 13975)
@@ -37,8 +37,4 @@
 		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.");};
@@ -47,3 +43,2 @@
 };
 #endif  /* _KML_OVERLAY_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Placemark.h	(revision 13975)
@@ -35,8 +35,4 @@
 		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.");};
@@ -45,3 +41,2 @@
 };
 #endif  /* _KML_PLACEMARK_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Point.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Point.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Point.h	(revision 13975)
@@ -37,8 +37,4 @@
 		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.");};
@@ -47,3 +43,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.cpp	(revision 13975)
@@ -65,5 +65,4 @@
 void  KML_PolyStyle::DeepEcho(const char* indent){
 
-	int   i;
 	bool  flag=true;
 
Index: /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h	(revision 13975)
@@ -33,8 +33,4 @@
 		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.");};
@@ -43,3 +39,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Polygon.cpp	(revision 13975)
@@ -250,5 +250,4 @@
 			}
 
-
 		else if (!strncmp(kstri,"<",1))
 			KML_Geometry::Read(fid,kstri);
Index: /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Polygon.h	(revision 13975)
@@ -41,8 +41,4 @@
 		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.");};
@@ -51,3 +47,2 @@
 };
 #endif  /* _KML_POLYGON_H */
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_Style.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Style.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Style.h	(revision 13975)
@@ -39,8 +39,4 @@
 		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.");};
@@ -49,3 +45,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.cpp	(revision 13975)
@@ -93,3 +93,2 @@
 }
 /*}}}*/
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h	(revision 13975)
@@ -30,8 +30,4 @@
 		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.");};
@@ -40,3 +36,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.cpp	(revision 13975)
@@ -93,3 +93,2 @@
 }
 /*}}}*/
-
Index: /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h	(revision 13975)
@@ -30,8 +30,4 @@
 		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.");};
@@ -40,3 +36,2 @@
 };
 #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 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Unknown.cpp	(revision 13975)
@@ -79,8 +79,8 @@
 		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);
@@ -110,8 +110,8 @@
 		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);
Index: /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h
===================================================================
--- /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/KML/KML_Unknown.h	(revision 13975)
@@ -33,8 +33,4 @@
 		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.");};
@@ -43,3 +39,2 @@
 };
 #endif  /* _KML_UNKNOWN_H */
-
Index: /issm/trunk/src/c/classes/objects/Loads/Friction.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Friction.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Friction.cpp	(revision 13975)
@@ -191,5 +191,4 @@
 
 	/*diverse: */
-	int     i;
 	IssmDouble  r,s;
 	IssmDouble  vx,vy,vz,vmag;
@@ -257,5 +256,4 @@
 
 	/*diverse: */
-	int     i;
 	IssmDouble  r,s;
 	IssmDouble  vx,vy,vz,vmag;
Index: /issm/trunk/src/c/classes/objects/Loads/Friction.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Friction.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Friction.h	(revision 13975)
@@ -25,5 +25,5 @@
 		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);
Index: /issm/trunk/src/c/classes/objects/Loads/Icefront.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Icefront.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Icefront.cpp	(revision 13975)
@@ -52,5 +52,5 @@
 	int  icefront_node_ids[NUMVERTICESQUA]; //initialize with largest size
 	int  icefront_fill;
-	
+
 	/*find parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -90,5 +90,5 @@
 	/*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;
@@ -104,5 +104,5 @@
 	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;
@@ -111,5 +111,4 @@
 	this->matpar= NULL;
 }
-
 
 /*}}}*/
@@ -157,10 +156,4 @@
 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){
@@ -172,5 +165,5 @@
 /*FUNCTION Icefront::copy {{{*/
 Object* Icefront::copy() {
-	
+
 	Icefront* icefront=NULL;
 
@@ -278,4 +271,56 @@
 }
 /*}}}*/
+/*FUNCTION Icefront::GetNodesSidList{{{*/
+void Icefront::GetNodesSidList(int* sidlist){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	switch(type){
+		case MacAyeal2dIceFrontEnum:
+		case MacAyeal3dIceFrontEnum:
+			for(int i=0;i<NUMVERTICESSEG;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+#ifdef _HAVE_3D_
+		case PattynIceFrontEnum:
+		case StokesIceFrontEnum:
+			for(int i=0;i<NUMVERTICESQUA;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+#endif
+		default:
+			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Icefront::GetNumberOfNodes{{{*/
+int Icefront::GetNumberOfNodes(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case MacAyeal2dIceFrontEnum:
+			return NUMVERTICESSEG;
+#ifdef _HAVE_3D_
+		case MacAyeal3dIceFrontEnum:
+			return NUMVERTICESSEG;
+		case PattynIceFrontEnum:
+			return NUMVERTICESQUA;
+		case StokesIceFrontEnum:
+			return NUMVERTICESQUA;
+#endif
+		default:
+			_error_("Icefront type " << EnumToStringx(type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Icefront::IsPenalty{{{*/
+bool Icefront::IsPenalty(void){
+	return false;
+}
+/*}}}*/
 /*FUNCTION Icefront::PenaltyCreateKMatrix {{{*/
 void  Icefront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax){
@@ -293,4 +338,55 @@
 void  Icefront::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
 	this->PenaltyCreateKMatrix(Jff,NULL,kmax);
+}
+/*}}}*/
+/*FUNCTION Icefront::SetwiseNodeConnectivity{{{*/
+void Icefront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<this->GetNumberOfNodes();i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
 }
 /*}}}*/
@@ -479,8 +575,7 @@
 ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal3d(void){
 
-	Icefront* icefront=NULL;
-	Penta*    penta=NULL;
-	Tria*     tria=NULL;
-	bool      onbed;
+	Icefront *icefront = NULL;
+	Penta    *penta    = NULL;
+	Tria     *tria     = NULL;
 
 	/*Cast element onto Penta*/
@@ -663,5 +758,4 @@
 void  Icefront::GetDofList(int** pdoflist,int approximation_enum,int setenum){
 
-	int i,j;
 	int numberofdofs=0;
 	int count=0;
@@ -672,5 +766,4 @@
 	int* doflist=NULL;
 
-	
 	/*recover type: */
 	inputs->GetInputValue(&type,TypeEnum);
@@ -678,5 +771,5 @@
 	/*Some checks for debugging*/
 	_assert_(nodes);
-		
+
 	/*How many nodes? :*/
 	if(type==MacAyeal2dIceFrontEnum || type==MacAyeal3dIceFrontEnum)
@@ -684,7 +777,7 @@
 	else 
 	 numberofnodes=4;
-	
+
 	/*Figure out size of doflist: */
-	for(i=0;i<numberofnodes;i++){
+	for(int i=0;i<numberofnodes;i++){
 		numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
 	}
@@ -695,5 +788,5 @@
 	/*Populate: */
 	count=0;
-	for(i=0;i<numberofnodes;i++){
+	for(int i=0;i<numberofnodes;i++){
 		nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
 		count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
Index: /issm/trunk/src/c/classes/objects/Loads/Icefront.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Icefront.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Icefront.h	(revision 13975)
@@ -48,5 +48,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -72,7 +71,11 @@
 		void  CreatePVector(Vector<IssmDouble>* pf);
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		int   GetNumberOfNodes(void);
+		void  GetNodesSidList(int* sidlist);
+		bool  IsPenalty(void);
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>*  pf, IssmDouble kmax);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		bool  InAnalysis(int analysis_type);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Load.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Load.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Load.h	(revision 13975)
@@ -4,5 +4,4 @@
  * It is derived from Load, so DataSets can contain them.
  */ 
-
 
 #ifndef _LOAD_H_
@@ -25,7 +24,8 @@
 
 		virtual       ~Load(){};
-		
-		/*Virtual functions: {{{*/
 		virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
+		virtual bool  IsPenalty(void)=0;
+		virtual int   GetNumberOfNodes(void)=0;
+		virtual void  GetNodesSidList(int* sidlist)=0;
 		virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
 		virtual void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
@@ -36,5 +36,5 @@
 		virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
 		virtual bool  InAnalysis(int analysis_type)=0;
-		/*}}}*/
+		virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
 };
 #endif
Index: /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp	(revision 13975)
@@ -34,5 +34,5 @@
 }
 /*}}}*/
-/*}}}*//*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{*/
+/*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){
 
@@ -175,5 +175,5 @@
 	_printLine_("   inputs");
 	inputs->DeepEcho();
-	
+
 }		
 /*}}}*/
@@ -183,10 +183,4 @@
 }
 /*}}}*/
-/*FUNCTION Numericalflux::MyRank {{{*/
-int    Numericalflux::MyRank(void){ 
-	extern int my_rank;
-	return my_rank; 
-}
-/*}}}*/
 /*FUNCTION Numericalflux::ObjectEnum{{{*/
 int Numericalflux::ObjectEnum(void){
@@ -198,5 +192,5 @@
 /*FUNCTION Numericalflux::copy {{{*/
 Object* Numericalflux::copy() {
-	
+
 	Numericalflux* numericalflux=NULL;
 
@@ -311,4 +305,46 @@
 }
 /*}}}*/
+/*FUNCTION Numericalflux::GetNodesSidList{{{*/
+void Numericalflux::GetNodesSidList(int* sidlist){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	switch(type){
+		case InternalEnum:
+			for(int i=0;i<NUMVERTICES_INTERNAL;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		case BoundaryEnum:
+			for(int i=0;i<NUMVERTICES_BOUNDARY;i++) sidlist[i]=nodes[i]->Sid();
+			return;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
+	}
+}
+/*}}}*/
+/*FUNCTION Numericalflux::GetNumberOfNodes{{{*/
+int Numericalflux::GetNumberOfNodes(void){
+
+	int type;
+	inputs->GetInputValue(&type,TypeEnum);
+
+	switch(type){
+		case InternalEnum:
+			return NUMVERTICES_INTERNAL;
+		case BoundaryEnum:
+			return NUMVERTICES_BOUNDARY;
+		default:
+			_error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
+	}
+
+}
+/*}}}*/
+/*FUNCTION Numericalflux::IsPenalty{{{*/
+bool Numericalflux::IsPenalty(void){
+	return false;
+}
+/*}}}*/
 /*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
 void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
@@ -331,4 +367,55 @@
 	if (in_analysis_type==this->analysis_type) return true;
 	else return false;
+}
+/*}}}*/
+/*FUNCTION Numericalflux::SetwiseNodeConnectivity{{{*/
+void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<this->GetNumberOfNodes();i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
 }
 /*}}}*/
@@ -410,5 +497,5 @@
 		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;
@@ -702,5 +789,5 @@
 
 	/* Intermediaries*/
-	int        i,j,ig,index1,index2;
+	int        i,ig,index1,index2;
 	IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
 	IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][3];
@@ -796,9 +883,9 @@
 
 	/* 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];
+	int        i,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;
 
Index: /issm/trunk/src/c/classes/objects/Loads/Numericalflux.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Numericalflux.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Numericalflux.h	(revision 13975)
@@ -20,18 +20,16 @@
 
 	public: 
-		int         id;
+		int id;
 		int analysis_type;
 
 		/*Hooks*/
-		Hook*       helement;
-		Hook*       hnodes;
+		Hook *helement;
+		Hook *hnodes;
 
 		/*Corresponding fields*/
-		Element* element;
-		Node**   nodes;
-
-		Parameters *parameters;
-		Inputs     *inputs;
-
+		Element     *element;
+		Node       **nodes;
+		Parameters  *parameters;
+		Inputs      *inputs;
 
 		/*Numericalflux constructors,destructors {{{*/
@@ -44,5 +42,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -67,8 +64,12 @@
 		void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
 		void  CreatePVector(Vector<IssmDouble>* pf);
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		bool  IsPenalty(void);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		bool  InAnalysis(int analysis_type);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp	(revision 13975)
@@ -19,5 +19,5 @@
 #include "../../../Container/Container.h"
 /*}}}*/
-	
+
 /*Element macros*/
 #define NUMVERTICES   1
@@ -34,5 +34,5 @@
 	this->hmatpar=NULL;
 	this->matpar=NULL;
-	
+
 	/*not active, not zigzagging: */
 	active=0;
@@ -44,5 +44,4 @@
 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;
@@ -64,5 +63,5 @@
 	this->id=id;
 	this->analysis_type=in_analysis_type;
-	
+
 	/*hooks: */
 	pengrid_node_id=iomodel->nodecounter+index+1;
@@ -99,5 +98,5 @@
 }
 /*}}}*/
-			
+
 /*Object virtual functions definitions:*/
 /*FUNCTION Pengrid::Echo {{{*/
@@ -126,10 +125,4 @@
 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){
@@ -140,5 +133,5 @@
 /*FUNCTION Icefront::copy {{{*/
 Object* Pengrid::copy() {
-	
+
 	Pengrid* pengrid=NULL;
 
@@ -214,4 +207,19 @@
 	return;
 
+}
+/*}}}*/
+/*FUNCTION Pengrid::GetNodesSidList{{{*/
+void Pengrid::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(node);
+
+	sidlist[0]=node->Sid();
+}
+/*}}}*/
+/*FUNCTION Pengrid::GetNumberOfNodes{{{*/
+int Pengrid::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
 }
 /*}}}*/
@@ -287,4 +295,56 @@
 }
 /*}}}*/
+/*FUNCTION Pengrid::IsPenalty{{{*/
+bool Pengrid::IsPenalty(void){
+	return true;
+}
+/*}}}*/
+/*FUNCTION Pengrid::SetwiseNodeConnectivity{{{*/
+void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	if(!flags[this->node->Sid()]){
+
+		/*flag current node so that no other element processes it*/
+		flags[this->node->Sid()]=true;
+
+		/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+		switch(set2_enum){
+			case FsetEnum:
+				if(node->indexing.fsize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			case GsetEnum:
+				if(node->indexing.gsize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			case SsetEnum:
+				if(node->indexing.ssize){
+					if(this->node->IsClone())
+					 o_nz += 1;
+					else
+					 d_nz += 1;
+				}
+				break;
+			default: _error_("not supported");
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
 
 /*Update virtual functions definitions:*/
@@ -401,5 +461,5 @@
 	/*recover pointers: */
 	Penta* penta=(Penta*)element;
-	
+
 	/*check that pengrid is not a clone (penalty to be added only once)*/
 	if (node->IsClone()){
@@ -415,5 +475,5 @@
 	//Recover our data:
 	parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
-	
+
 	//Compute pressure melting point
 	t_pmp=matpar->TMeltingPoint(pressure);
@@ -427,5 +487,4 @@
 		new_active=0;
 	}
-
 
 	//Figure out stability of this penalty
@@ -456,5 +515,5 @@
 /*FUNCTION Pengrid::PenaltyCreateKMatrixDiagnosticStokes {{{*/
 ElementMatrix* Pengrid::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
-	
+
 	const int numdof = NUMVERTICES *NDOF4;
 	IssmDouble    slope[2];
@@ -505,5 +564,5 @@
 	penta->GetInputValue(&temperature,node,TemperatureEnum);
 	parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
-	
+
 	/*Compute pressure melting point*/
 	t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
@@ -539,5 +598,5 @@
 /*FUNCTION Pengrid::PenaltyCreatePVectorMelting {{{*/
 ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){
-	
+
 	const int numdof=NUMVERTICES*NDOF1;
 	IssmDouble pressure;
Index: /issm/trunk/src/c/classes/objects/Loads/Pengrid.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Pengrid.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Pengrid.h	(revision 13975)
@@ -20,5 +20,5 @@
 		int		id;
 		int analysis_type;
-		
+
 		/*Hooks*/
 		Hook* hnode;  //hook to 1 node
@@ -33,5 +33,5 @@
 		Parameters* parameters; //pointer to solution parameters
 		Inputs*  inputs;
-	
+
 		/*internals: */
 		int active;
@@ -49,5 +49,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -73,7 +72,11 @@
 		void  CreatePVector(Vector<IssmDouble>* pf);
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		bool  InAnalysis(int analysis_type);
 		/*}}}*/
@@ -97,4 +100,2 @@
 
 #endif  /* _PENGRID_H_ */
-
-
Index: /issm/trunk/src/c/classes/objects/Loads/Penpair.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Penpair.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Penpair.cpp	(revision 13975)
@@ -34,5 +34,5 @@
 /*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;
@@ -40,5 +40,5 @@
 	this->parameters=NULL;
 	this->nodes=NULL;
-	
+
 	return;
 }
@@ -54,6 +54,4 @@
 /*FUNCTION Penpair::Echo {{{*/
 void Penpair::Echo(void){
-
-	int i;
 
 	_printLine_("Penpair:");
@@ -61,5 +59,5 @@
 	_printLine_("   analysis_type: " << EnumToStringx(analysis_type));
 	hnodes->Echo();
-	
+
 	return;
 }
@@ -79,10 +77,4 @@
 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){
@@ -93,5 +85,5 @@
 /*FUNCTION Penpair::copy {{{*/
 Object* Penpair::copy() {
-	
+
 	Penpair* penpair=NULL;
 
@@ -113,5 +105,5 @@
 }
 /*}}}*/
-		
+
 /*Load virtual functions definitions:*/
 /*FUNCTION Penpair::Configure {{{*/
@@ -154,4 +146,24 @@
 void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
 	this->CreateKMatrix(Jff,NULL);
+}
+/*}}}*/
+/*FUNCTION Penpair::GetNodesSidList{{{*/
+void Penpair::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+/*FUNCTION Penpair::GetNumberOfNodes{{{*/
+int Penpair::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
+}
+/*}}}*/
+/*FUNCTION Penpair::IsPenalty{{{*/
+bool Penpair::IsPenalty(void){
+	return true;
 }
 /*}}}*/
@@ -197,4 +209,55 @@
 	if (in_analysis_type==this->analysis_type)return true;
 	else return false;
+}
+/*}}}*/
+/*FUNCTION Penpair::SetwiseNodeConnectivity{{{*/
+void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<NUMVERTICES;i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
 }
 /*}}}*/
@@ -270,5 +333,5 @@
 /*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{*/
 ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax){
-	
+
 	const int numdof=NUMVERTICES*NDOF2;
 	IssmDouble penalty_offset;
@@ -297,5 +360,5 @@
 /*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{*/
 ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
-	
+
 	const int numdof=NUMVERTICES*NDOF4;
 	IssmDouble penalty_offset;
@@ -317,5 +380,5 @@
 	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);
Index: /issm/trunk/src/c/classes/objects/Loads/Penpair.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Penpair.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Penpair.h	(revision 13975)
@@ -17,11 +17,9 @@
 
 	private: 
-		int		id;
-		int analysis_type;
-		
-		Hook* hnodes;  //hook to 2 nodes
-		Node** nodes;
-
-		Parameters* parameters; //pointer to solution parameters
+		int          id;
+		int          analysis_type;
+		Hook        *hnodes;          //hook to 2 nodes
+		Node       **nodes;
+		Parameters  *parameters;      //pointer to solution parameters
 
 	public:
@@ -36,5 +34,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -60,7 +57,11 @@
 		void  CreatePVector(Vector<IssmDouble>* pf);
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		bool  InAnalysis(int analysis_type);
 		/*}}}*/
@@ -74,4 +75,2 @@
 
 #endif  /* _PENPAIR_H_ */
-
-
Index: /issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp	(revision 13975)
@@ -97,5 +97,5 @@
 	//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));
@@ -109,5 +109,5 @@
 	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;
@@ -115,5 +115,5 @@
 	this->elements= NULL;
 	this->matpar= NULL;
-		
+
 }
 /*}}}*/
@@ -137,5 +137,4 @@
 	IssmDouble friction,fractionincrement;
 
-	
 	/*recover some inputs first: */
 	input=(Input*)this->inputs->GetInput(FillEnum); input->GetInputValue(&fill);
@@ -165,5 +164,5 @@
 	_printLine_("   state: " << state);
 	_printLine_("   frozen: " << (frozen ? "true":"false"));
-		
+
 }
 /*}}}*/
@@ -186,10 +185,4 @@
 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){
@@ -201,5 +194,5 @@
 /*FUNCTION Riftfront::copy {{{*/
 Object* Riftfront::copy() {
-	
+
 	Riftfront* riftfront=NULL;
 
@@ -240,10 +233,10 @@
 	riftfront->length=this->length;
 	riftfront->fraction=this->fraction;
-	
+
 	return riftfront;
 
 }
 /*}}}*/
-		
+
 /*Update virtual functions definitions:*/
 /*FUNCTION Riftfront::InputUpdateFromConstant(bool constant,int name) {{{*/
@@ -281,5 +274,4 @@
 }
 /*}}}*/
-
 
 /*Load virtual functions definitions:*/
@@ -301,4 +293,9 @@
 	this->parameters=parametersin;
 
+}
+/*}}}*/
+/*FUNCTION Riftfront::IsPenalty{{{*/
+bool Riftfront::IsPenalty(void){
+	return true;
 }
 /*}}}*/
@@ -372,4 +369,19 @@
 }
 /*}}}*/
+/*FUNCTION Riftfront::GetNodesSidList{{{*/
+void Riftfront::GetNodesSidList(int* sidlist){
+
+	_assert_(sidlist);
+	_assert_(nodes);
+
+	for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
+}
+/*}}}*/
+/*FUNCTION Riftfront::GetNumberOfNodes{{{*/
+int Riftfront::GetNumberOfNodes(void){
+
+	return NUMVERTICES;
+}
+/*}}}*/
 /*FUNCTION Riftfront::InAnalysis{{{*/
 bool Riftfront::InAnalysis(int in_analysis_type){
@@ -378,4 +390,55 @@
 }
 /*}}}*/
+/*FUNCTION Riftfront::SetwiseNodeConnectivity{{{*/
+void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
+
+	/*Output */
+	int d_nz = 0;
+	int o_nz = 0;
+
+	/*Loop over all nodes*/
+	for(int i=0;i<NUMVERTICES;i++){
+
+		if(!flags[this->nodes[i]->Sid()]){
+
+			/*flag current node so that no other element processes it*/
+			flags[this->nodes[i]->Sid()]=true;
+
+			/*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
+			switch(set2_enum){
+				case FsetEnum:
+					if(nodes[i]->indexing.fsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case GsetEnum:
+					if(nodes[i]->indexing.gsize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				case SsetEnum:
+					if(nodes[i]->indexing.ssize){
+						if(this->nodes[i]->IsClone())
+						 o_nz += 1;
+						else
+						 d_nz += 1;
+					}
+					break;
+				default: _error_("not supported");
+			}
+		}
+	}
+
+	/*Assign output pointers: */
+	*pd_nz=d_nz;
+	*po_nz=o_nz;
+}
+/*}}}*/
 
 /*Riftfront numerics*/
@@ -384,11 +447,9 @@
 
 	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;
+	IssmDouble  thickness;
+	IssmDouble  h[2];
+	IssmDouble  penalty_offset;
+	IssmDouble  friction;
 
 	/*Objects: */
@@ -466,24 +527,24 @@
 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;
+	const int  numdof = NDOF2*NUMVERTICES;
+	int        j;
+	IssmDouble rho_ice;
+	IssmDouble rho_water;
+	IssmDouble gravity;
+	IssmDouble thickness;
+	IssmDouble h[2];
+	IssmDouble bed;
+	IssmDouble b[2];
+	IssmDouble pressure;
+	IssmDouble pressure_litho;
+	IssmDouble pressure_air;
+	IssmDouble pressure_melange;
+	IssmDouble pressure_water;
+	int        fill;
+	bool       shelf;
 
 	/*Objects: */
-	Tria       *tria1               = NULL;
-	Tria       *tria2               = NULL;
+	Tria *tria1 = NULL;
+	Tria *tria2 = NULL;
 
 	/*enum of element? */
@@ -569,8 +630,6 @@
 
 	const int   numnodes        = 2;
-	IssmDouble      max_penetration;
 	IssmDouble      penetration;
 	int         activate;
-	int         found;
 	int         unstable;
 	IssmDouble      vx1;
@@ -602,10 +661,9 @@
 		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: */
@@ -674,5 +732,4 @@
 int   Riftfront::IsMaterialStable(void){
 
-	int found=0;
 	IssmDouble converged=0;
 
@@ -693,7 +750,5 @@
 
 	const int     numnodes=2;
-	IssmDouble        max_penetration;
 	IssmDouble        penetration=0;
-	int           found;
 	IssmDouble      vx1;
 	IssmDouble      vy1;
@@ -729,5 +784,5 @@
 	/*If we are zigzag locked, same thing: */
 	if(this->counter>this->penalty_lock)penetration=-1;
-	
+
 	/*assign output pointer: */
 	*ppenetration=penetration;
@@ -744,5 +799,4 @@
 
 	IssmDouble    penetration;
-	int       found;
 
 	/*Objects: */
@@ -768,5 +822,5 @@
 	/*Now, we return penetration only if we are active!: */
 	if(this->active==0)penetration=0;
-	
+
 	/*assign output pointer: */
 	*ppenetration=penetration;
@@ -777,19 +831,15 @@
 int   Riftfront::PotentialUnstableConstraint(int* punstable){
 
-
 	const int   numnodes        = 2;
-	IssmDouble      max_penetration;
-	IssmDouble      penetration;
-	int         activate;
+	IssmDouble  penetration;
 	int         unstable;
-	int         found;
-	IssmDouble      vx1;
-	IssmDouble      vy1;
-	IssmDouble      vx2;
-	IssmDouble      vy2;
+	IssmDouble  vx1;
+	IssmDouble  vy1;
+	IssmDouble  vx2;
+	IssmDouble  vy2;
 
 	/*Objects: */
-	Tria       *tria1           = NULL;
-	Tria       *tria2           = NULL;
+	Tria       *tria1 = NULL;
+	Tria       *tria2 = NULL;
 
 	/*enum of element? */
@@ -833,5 +883,4 @@
 	IssmDouble      penetration;
 	int         unstable;
-	int         found;
 	IssmDouble      vx1;
 	IssmDouble      vy1;
Index: /issm/trunk/src/c/classes/objects/Loads/Riftfront.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Loads/Riftfront.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Loads/Riftfront.h	(revision 13975)
@@ -25,5 +25,5 @@
 		Hook* helements;
 		Hook* hmatpar;
-		
+
 		/*Corresponding fields*/
 		Matpar   *matpar;
@@ -32,18 +32,17 @@
 
 		/*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;
+		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: {{{*/
@@ -56,5 +55,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -80,7 +78,11 @@
 		void  CreatePVector(Vector<IssmDouble>* pf);
 		void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
+		void  GetNodesSidList(int* sidlist);
+		int   GetNumberOfNodes(void);
+		bool  IsPenalty(void);
 		void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
 		void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
 		void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
+		void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
 		bool  InAnalysis(int analysis_type);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
-		
+
 /*Matdamageice constructors and destructor*/
 /*FUNCTION Matdamageice::Matdamageice(){{{*/
@@ -28,5 +28,4 @@
 
 	/*Intermediaries:*/
-	int    i;
 	int    matice_eid;
 
@@ -82,10 +81,4 @@
 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){
@@ -210,5 +203,5 @@
 			/*Prepare index list*/
 			int doflist1[3];
-			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
+			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexPid();
 
 			/*Get input (either in element or material)*/
@@ -305,5 +298,5 @@
 	 * return g, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity3d;
@@ -347,5 +340,5 @@
 			else{
 				e=(n-1)/2/n;
-			
+
 				viscosity3d=B/(2*pow(A,e));
 			}
@@ -376,5 +369,5 @@
 	 * return g, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity3d;
@@ -393,5 +386,5 @@
 	Z=GetZ();
 	B=Z*GetB();
-	
+
 	if (n==1){
 		/*Viscous behaviour! viscosity3d=B: */
@@ -446,5 +439,5 @@
 	 * return mu20, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity_complement;
@@ -474,5 +467,5 @@
 		else{
 			e=(n-1)/(2*n);
-		
+
 			viscosity_complement=1/(2*pow(A,e));
 		}
@@ -486,5 +479,5 @@
 	_assert_(n>0);
 	_assert_(viscosity_complement>0);
-		
+
 	/*Return: */
 	*pviscosity_complement=viscosity_complement;
@@ -502,5 +495,5 @@
 	 * return mu20, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity_complement;
@@ -530,5 +523,5 @@
 		else{
 			e=(n-1)/(2*n);
-		
+
 			viscosity_complement=B/(2*pow(A,e));
 		}
@@ -542,5 +535,5 @@
 	_assert_(n>0);
 	_assert_(viscosity_complement>0);
-		
+
 	/*Return: */
 	*pviscosity_complement=viscosity_complement;
@@ -589,5 +582,5 @@
 
 	/*input strain rate: */
-	IssmDouble exx,eyy,exy,exz;
+	IssmDouble exx,eyy,exy;
 
 	/*Get visocisty and n*/
@@ -640,5 +633,5 @@
 				case TriaEnum: {
 					IssmDouble values[3];
-					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexPid()];
 					this->inputs->AddInput(new TriaP1Input(name,values));
 					return;
@@ -682,5 +675,5 @@
 				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 
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexSid()]; //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{{{*/
@@ -706,6 +699,4 @@
 		default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
 	}
-
-
 
 }
Index: /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matdamageice.h	(revision 13975)
@@ -28,5 +28,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Materials/Material.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Material.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Material.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief abstract class for Material object
  */ 
-
 
 #ifndef _MATERIAL_H_
Index: /issm/trunk/src/c/classes/objects/Materials/Matice.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matice.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matice.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
-		
+
 /*Matice constructors and destructor*/
 /*FUNCTION Matice::Matice(){{{*/
@@ -28,5 +28,4 @@
 
 	/*Intermediaries:*/
-	int    i;
 	int    matice_eid;
 
@@ -82,10 +81,4 @@
 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){
@@ -190,5 +183,5 @@
 			/*Prepare index list*/
 			int doflist1[3];
-			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
+			for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexPid();
 
 			/*Get input (either in element or material)*/
@@ -283,5 +276,5 @@
 	 * return g, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity3d;
@@ -324,5 +317,5 @@
 			else{
 				e=(n-1)/2/n;
-			
+
 				viscosity3d=B/(2*pow(A,e));
 			}
@@ -353,5 +346,5 @@
 	 * return g, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity3d;
@@ -369,5 +362,5 @@
 	B=GetB();
 	n=GetN();
-	
+
 	if (n==1){
 		/*Viscous behaviour! viscosity3d=B: */
@@ -422,5 +415,5 @@
 	 * return mu20, initial viscosity.
 	 */
-	
+
 	/*output: */
 	IssmDouble viscosity_complement;
@@ -450,5 +443,5 @@
 		else{
 			e=(n-1)/(2*n);
-		
+
 			viscosity_complement=1/(2*pow(A,e));
 		}
@@ -462,5 +455,5 @@
 	_assert_(n>0);
 	_assert_(viscosity_complement>0);
-		
+
 	/*Return: */
 	*pviscosity_complement=viscosity_complement;
@@ -509,5 +502,5 @@
 
 	/*input strain rate: */
-	IssmDouble exx,eyy,exy,exz;
+	IssmDouble exx,eyy,exy;
 
 	/*Get visocisty and n*/
@@ -560,5 +553,5 @@
 				case TriaEnum: {
 					IssmDouble values[3];
-					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexPid()];
 					this->inputs->AddInput(new TriaP1Input(name,values));
 					return;
@@ -602,5 +595,5 @@
 				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 
+					for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexSid()]; //index into serial oriented vector 
 					this->inputs->AddInput(new TriaP1Input(name,values));
 					/*Special case for rheology B in 2D: Pourave land for this solution{{{*/
@@ -627,6 +620,4 @@
 	}
 
-
-
 }
 /*}}}*/
Index: /issm/trunk/src/c/classes/objects/Materials/Matice.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matice.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matice.h	(revision 13975)
@@ -15,6 +15,6 @@
 
 	private: 
-		int	   mid;
-		Hook* helement;
+		int   mid;
+		Hook *helement;
 
 	public:
@@ -28,5 +28,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
Index: /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matpar.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 #include "../../../include/include.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-		
+
 /*Matpar constructors and destructor*/
 /*FUNCTION Matpar::Matpar() {{{*/
@@ -39,5 +39,5 @@
 	iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
 	iomodel->Constant(&this->g,ConstantsGEnum);
-	
+
 	iomodel->Constant(&this->hydro_CR,HydrologyCREnum);
 	iomodel->Constant(&this->kn,HydrologyKnEnum);
@@ -85,10 +85,4 @@
 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){
@@ -250,5 +244,5 @@
 /*FUNCTION Matpar::GetRhoIce {{{*/
 IssmDouble Matpar::GetRhoIce(){
-	
+
 	return rho_ice;
 }
@@ -329,5 +323,5 @@
 	/*Ouput*/
 	IssmDouble temperature,waterfraction;
-	
+
 	if(enthalpy<PureIceEnthalpy(pressure)){
 		temperature=referencetemperature+enthalpy/heatcapacity;
@@ -349,5 +343,5 @@
 	/*Ouput*/
 	IssmDouble enthalpy;
-	
+
 	if(temperature<TMeltingPoint(pressure)){
 		enthalpy=heatcapacity*(temperature-referencetemperature);
Index: /issm/trunk/src/c/classes/objects/Materials/Matpar.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Materials/Matpar.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Materials/Matpar.h	(revision 13975)
@@ -43,10 +43,9 @@
 
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy();
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy();
 		/*}}}*/
 		/*Update virtual functions resolution: {{{*/
Index: /issm/trunk/src/c/classes/objects/Node.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Node.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Node.cpp	(revision 13975)
@@ -58,11 +58,11 @@
 	this->inputs=new Inputs();
 	if (iomodel->Data(MeshVertexonbedEnum))
-	 this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonbedEnum)[io_index])));
+	 this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index])));
 	if (iomodel->Data(MeshVertexonsurfaceEnum))
-	 this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index])));
+	 this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,reCast<bool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index])));
 	if (iomodel->Data(MaskVertexonfloatingiceEnum))
-	 this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
+	 this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<bool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
 	if (iomodel->Data(MaskVertexongroundediceEnum))
-	  this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
+	  this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<bool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
 	if (analysis_type==DiagnosticHorizAnalysisEnum)
 	 this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<IssmInt>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])));
@@ -71,5 +71,5 @@
 	/*spc all nodes on water*/
 	if (!iomodel->Data(MaskVertexonwaterEnum)) _error_("iomodel->nodeonwater is NULL");
-	if (reCast<IssmBool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
+	if (reCast<bool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
 		for(k=1;k<=gsize;k++){
 			this->FreezeDof(k);
@@ -137,5 +137,5 @@
 			/*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]))){
+			if (!(reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
 				for(k=1;k<=gsize;k++){
 					this->FreezeDof(k);
@@ -166,5 +166,4 @@
 	_printLine_("   hvertex:     not displayed");
 	_printLine_("   inputs:      " << inputs);
-
 
 }
@@ -182,16 +181,8 @@
 	_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{{{*/
@@ -234,14 +225,4 @@
 
 } /*}}}*/
-/*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){
@@ -249,5 +230,5 @@
 	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];
@@ -306,14 +287,4 @@
 }
 /*}}}*/
-/*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){
@@ -321,5 +292,5 @@
 	int count=0;
 	int count2=0;
-		
+
 	if(approximation_enum==NoneApproximationEnum){
 		if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
@@ -427,11 +398,21 @@
 }
 /*}}}*/
-/*FUNCTION Node::GetVertexDof {{{*/
-int   Node::GetVertexDof(void){
+/*FUNCTION Node::GetVertexPid{{{*/
+int   Node::GetVertexPid(void){
 
 	Vertex*  vertex=NULL;
 
 	vertex=(Vertex*)hvertex->delivers();
-	return vertex->dof;
+	return vertex->pid;
+}
+/*}}}*/
+/*FUNCTION Node::GetVertexSid{{{*/
+int  Node::GetVertexSid(void){
+
+	Vertex* vertex=NULL;
+
+	vertex=(Vertex*)this->hvertex->delivers();
+
+	return vertex->sid;
 }
 /*}}}*/
@@ -446,14 +427,4 @@
 /*}}}*/
 #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){
@@ -467,6 +438,4 @@
 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*/
@@ -495,5 +464,5 @@
 		/*g set: */
 		pv_g->SetValue(indexing.gdoflist[i],gvalue,INS_VAL);
-		
+
 		/*f set: */
 		value=(IssmDouble)this->indexing.f_set[i];
@@ -505,5 +474,4 @@
 
 	}
-
 
 }
@@ -527,5 +495,5 @@
 			}
 		}
-		
+
 		/*Add values into constraint vector: */
 		ys->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
@@ -535,5 +503,4 @@
 	xDelete<IssmDouble>(values);
 
-
 }
 /*}}}*/
@@ -560,5 +527,5 @@
 /*FUNCTION Node::FreezeDof{{{*/
 void  Node::FreezeDof(int dof){
-	
+
 	DofInSSet(dof-1); //with 0 displacement for this dof.
 
@@ -589,5 +556,5 @@
 	/*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;
@@ -666,5 +633,5 @@
 /*FUNCTION Node::IsClone {{{*/
 int   Node::IsClone(){
-	
+
 	return indexing.clone;
 
@@ -695,5 +662,5 @@
 /*FUNCTION Node::IsFloating {{{*/
 int   Node::IsFloating(){
-	
+
 	bool onshelf;
 
@@ -887,10 +854,9 @@
 /*}}}*/
 
-/* DofObject routines:*/
+/* indexing routines:*/
 /*FUNCTION Node::DistributeDofs{{{*/
 void  Node::DistributeDofs(int* pdofcount,int setenum){
 
 	int i;
-	extern int my_rank;
 	int dofcount;
 
@@ -900,6 +866,5 @@
 	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){
@@ -908,5 +873,4 @@
 
 	/*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++){
@@ -929,16 +893,13 @@
 	else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
 
-
 	/*Assign output pointers: */
 	*pdofcount=dofcount;
-
-}
-/*}}}*/
-/*FUNCTION Node::Off_setDofs{{{*/
+}
+/*}}}*/
+/*FUNCTION Node::OffsetDofs{{{*/
 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!: */
@@ -963,14 +924,22 @@
 
 	int j;
-	extern int my_rank;
-	
+
 	/*Are we a clone? : */
-	if(indexing.clone)return;
+	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!");
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) truedofs[ncols*sid+j]=indexing.gdoflist[j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) truedofs[ncols*sid+j]=indexing.fdoflist[j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) truedofs[ncols*sid+j]=indexing.sdoflist[j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
 
 }
@@ -980,17 +949,23 @@
 
 	int j;
-	extern int my_rank;
-	
+
 	/*If we are not a clone, don't update, we already have dofs!: */
-	if(indexing.clone==0)return;
-
+	if(!indexing.clone)return;
 
 	/*Ok, we are a clone node, but we did not create the dofs for this node.
-	 *      * Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
-	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!");
-
+	 *Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
+	switch(setenum){
+		case GsetEnum:
+			for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case FsetEnum:
+			for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		case SsetEnum:
+			for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=alltruedofs[ncols*sid+j];
+			break;
+		default:
+			_error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
+	}
 }
 /*}}}*/
@@ -998,15 +973,17 @@
 void  Node::SetClone(int* minranks){
 
-	extern int my_rank;
+	int my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	if (minranks[sid]==my_rank){
-		indexing.clone=0;
+		indexing.clone=false;
 	}
 	else{
 		/*!there is a cpu with lower rank that has the same node, 
 		therefore, I am a clone*/
-		indexing.clone=1; 	
-	}
-
-}
-/*}}}*/
+		indexing.clone=true;	
+	}
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Node.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Node.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Node.h	(revision 13975)
@@ -25,12 +25,12 @@
 	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];
+		int id;    //unique arbitrary id.
+		int sid;   //"serial" id (rank of this node if the dataset was serial on 1 cpu)
+
+		DofIndexing  indexing;
+		Hook        *hvertex;
+		Inputs      *inputs;               //properties of this node
+		int          analysis_type;
+		IssmDouble   coord_system[3][3];
 
 		/*Node constructors, destructors {{{*/
@@ -40,13 +40,11 @@
 		/*}}}*/
 		/*Object virtual functions definitions:{{{ */
-		void  Echo();
-		void  DeepEcho();
-		int   Id(); 
-		int   MyRank();
-		int   ObjectEnum();
-		Object* copy(){_error_("Not implemented yet (similar to Elements)");};
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy()        {_error_("Not implemented yet (similar to Elements)"); };
 		/*}}}*/
 		/*Update virtual functions definitions: {{{*/
-		
 		void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
 		void  InputUpdateFromVector(int* vector, int name, int type);
@@ -67,10 +65,7 @@
 		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();
@@ -86,6 +81,7 @@
 		void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
 		void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
-		int    GetDofList1(void);
-		int    GetSidList(void);
+		int    GetVertexId(void);
+		int    GetVertexPid(void);
+		int    GetVertexSid(void);
 		IssmDouble GetX();
 		IssmDouble GetY();
@@ -100,7 +96,4 @@
 		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);
Index: /issm/trunk/src/c/classes/objects/Object.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Object.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Object.h	(revision 13975)
@@ -7,5 +7,4 @@
  * DataSet.
  */
-
 
 #ifndef _OBJECT_H_
@@ -20,5 +19,4 @@
 		virtual void  DeepEcho()=0;
 		virtual int   Id()=0;
-		virtual int   MyRank()=0;
 		virtual int   ObjectEnum()=0;
 		virtual Object* copy()=0;
Index: /issm/trunk/src/c/classes/objects/Options/GenericOption.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/GenericOption.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Options/GenericOption.h	(revision 13975)
@@ -29,10 +29,10 @@
 	public:
 
-		char* name;
-		OptionType value;
+		char       *name;
+		OptionType  value;
 
-		int   numel; //in case OptionType is an array
-		int   ndims; //in case OptionType is a multi-dimensional array: */
-		int*  size;
+		int         numel;   //in case OptionType is an array
+		int         ndims;   //in case OptionType is a multi-dimensional array: */
+		int        *size;
 
 		/*GenericOption constructors, destructors*/
@@ -43,5 +43,4 @@
 			ndims =0;
 			size  =NULL;
-
 
 		} /*}}}*/
@@ -81,8 +80,7 @@
 		} /*}}}*/
 		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;};
@@ -93,5 +91,5 @@
 };
 
-#ifdef _HAVE_ADOLC_ //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)  //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization. 
 template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
 
@@ -115,9 +113,6 @@
 template <> inline void GenericOption<char*>::Get(char** pvalue){ /*{{{*/
 
-	char* outstring=NULL;
-	int   stringsize;
-
-	stringsize=strlen(this->value)+1;
-	outstring=xNew<char>(stringsize);
+	int   stringsize=strlen(this->value)+1;
+	char* outstring=xNew<char>(stringsize);
 	xMemCpy<char>(outstring,this->value,stringsize);
 
Index: /issm/trunk/src/c/classes/objects/Options/Option.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/Option.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Options/Option.h	(revision 13975)
@@ -18,18 +18,15 @@
 	public:
 
-		
-		/*Option constructors, destructors {{{*/
+		/*Option constructors, destructors*/
 		Option(){};
 		~Option(){};
-		/*}}}*/
-		/*Object virtual functions definitions:{{{*/
+
+		/*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: */
@@ -41,3 +38,2 @@
 };
 #endif  /* _OPTIONOBJECT_H */
-
Index: /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Options/OptionUtilities.h	(revision 13975)
@@ -22,3 +22,2 @@
 
 #endif  /* _OPTIONUTILITIES_H */
-
Index: /issm/trunk/src/c/classes/objects/Params/BoolParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/BoolParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/BoolParam.cpp	(revision 13975)
@@ -26,6 +26,6 @@
 }
 /*}}}*/
-/*FUNCTION BoolParam::BoolParam(int enum_type,IssmBool value){{{*/
-BoolParam::BoolParam(int in_enum_type,IssmBool in_value){
+/*FUNCTION BoolParam::BoolParam(int enum_type,bool value){{{*/
+BoolParam::BoolParam(int in_enum_type,bool in_value){
 
 	enum_type=in_enum_type;
@@ -56,10 +56,4 @@
 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){
@@ -71,5 +65,5 @@
 /*FUNCTION BoolParam::copy{{{*/
 Object* BoolParam::copy() {
-	
+
 	return new BoolParam(this->enum_type,this->value);
 
Index: /issm/trunk/src/c/classes/objects/Params/BoolParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/BoolParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/BoolParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _BOOLPARAM_H_
@@ -25,9 +24,9 @@
 		/*just hold 3 values for 3 vertices: */
 		int enum_type;
-		IssmBool value;
+		bool value;
 
 		/*BoolParam constructors, destructors: {{{*/
 		BoolParam();
-		BoolParam(int enum_type,IssmBool value);
+		BoolParam(int enum_type,bool value);
 		~BoolParam();
 		/*}}}*/
@@ -36,5 +35,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -56,4 +54,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){this->value=boolean;}
@@ -71,5 +70,5 @@
 		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);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/DataSetParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DataSetParam.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/Params/DataSetParam.cpp	(revision 13975)
@@ -0,0 +1,89 @@
+/*!\file DataSetParam.c
+ * \brief: implementation of the DataSetParam object
+ */
+
+/*header files: */
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "../objects.h"
+#include "../../../EnumDefinitions/EnumDefinitions.h"
+#include "../../../shared/shared.h"
+#include "../../../Container/Container.h"
+#include "../../../include/include.h"
+/*}}}*/
+
+/*DataSetParam constructors and destructor*/
+/*FUNCTION DataSetParam::DataSetParam(){{{*/
+DataSetParam::DataSetParam(){
+	value=NULL;
+	return;
+}
+/*}}}*/
+/*FUNCTION DataSetParam::DataSetParam(int enum_type,DataSet *value){{{*/
+DataSetParam::DataSetParam(int in_enum_type,DataSet* in_value){
+
+	enum_type=in_enum_type;
+	value=in_value->Copy();;
+}
+/*}}}*/
+/*FUNCTION DataSetParam::~DataSetParam(){{{*/
+DataSetParam::~DataSetParam(){
+	delete value;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION DataSetParam::Echo {{{*/
+void DataSetParam::Echo(void){
+	this->DeepEcho();
+}
+/*}}}*/
+/*FUNCTION DataSetParam::DeepEcho{{{*/
+void DataSetParam::DeepEcho(void){
+
+	_printLine_("DataSetParam:");
+	_printLine_("   enum:  " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
+	this->value->Echo();
+}
+/*}}}*/
+/*FUNCTION DataSetParam::Id{{{*/
+int    DataSetParam::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION DataSetParam::ObjectEnum{{{*/
+int DataSetParam::ObjectEnum(void){
+
+	return DataSetParamEnum;
+
+}
+/*}}}*/
+/*FUNCTION DataSetParam::copy{{{*/
+Object* DataSetParam::copy() {
+
+	return new DataSetParam(this->enum_type,this->value);
+
+}
+/*}}}*/
+
+/*DataSetParam virtual functions definitions: */
+/*FUNCTION DataSetParam::GetParameterName{{{*/
+void DataSetParam::GetParameterName(char**pname){
+	EnumToStringx(pname,this->enum_type);
+}
+/*}}}*/
+/*FUNCTION DataSetParam::UnitConversion{{{*/
+void  DataSetParam::UnitConversion(int direction_enum){
+	/*do nothing, no unit conversion*/
+}
+/*}}}*/
+/*FUNCTION DataSetParam::GetParameterValue{{{*/
+void DataSetParam::GetParameterValue(DataSet** pdataset){
+	*pdataset=value->Copy();
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/DataSetParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DataSetParam.h	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/Params/DataSetParam.h	(revision 13975)
@@ -0,0 +1,78 @@
+/*! \file DataSetParam.h 
+ *  \brief: header file for triavertexinput object
+ */
+
+#ifndef _DATASETPARAM_H_
+#define _DATASETPARAM_H_
+
+/*Headers:*/
+/*{{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Param.h"
+#include "../../../include/include.h"
+#include "../../../shared/shared.h"
+/*}}}*/
+
+class DataSetParam: public Param{
+
+	private: 
+		int   enum_type;
+		DataSet* value;
+
+	public:
+		/*DataSetParam constructors, destructors: {{{*/
+		DataSetParam();
+		DataSetParam(int enum_type,DataSet* dataset);
+		~DataSetParam();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void  Echo();
+		void  DeepEcho();
+		int   Id(); 
+		int   ObjectEnum();
+		Object* copy();
+		/*}}}*/
+		/*Param vritual function definitions: {{{*/
+		int   InstanceEnum(){return enum_type;}
+		void  GetParameterValue(bool* pbool){  _error_("Param "<< EnumToStringx(enum_type) << " cannot return a bool");}
+		void  GetParameterValue(int* pinteger){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(int** pintarray,int* pM,int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pIssmDouble){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble");}
+		void  GetParameterValue(IssmDouble* pdouble,IssmDouble time){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble for a given time");}
+		void  GetParameterValue(FILE** pfile){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a file pointer");}
+		void  GetParameterValue(char** pstring){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string");}
+		void  GetParameterValue(char*** pstringarray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a string array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble** pIssmDoublearray,int* pM, int* pN){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a IssmDouble array");}
+		void  GetParameterValue(IssmDouble*** parray, int* pM,int** pmdims, int** pndims){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a matrix array");}
+		void  GetParameterValue(Vector<IssmDouble>** pvec){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Vec");}
+		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
+		void  GetParameterValue(DataSet** pdataset);
+
+		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(int integer){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(IssmDouble scalar){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(char* string){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
+		void  SetValue(FILE* fid){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a file pointer");}
+		void  SetValue(char** stringarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string array");}
+		void  SetValue(IssmDouble* IssmDoublearray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(IssmDouble* pIssmDoublearray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a IssmDouble array");}
+		void  SetValue(int* intarray,int M){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(int* pintarray,int M,int N){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a int array");}
+		void  SetValue(Vector<IssmDouble>* vec){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Vec");}
+		void  SetValue(Matrix<IssmDouble>* mat){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a Mat");}
+		void  SetValue(DataSet* dataset){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a DataSet yet");}
+		void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("DataSet param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold an array of matrices");}
+		void  UnitConversion(int direction_enum);
+
+		void GetParameterName(char**pname);
+
+		/*}}}*/
+};
+#endif  /* _INTPARAM_H */
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp	(revision 13975)
@@ -77,5 +77,5 @@
 		xDelete<IssmDouble>(matrix);
 	}
-	
+
 	xDelete<IssmDouble*>(array);
 	return;
@@ -100,5 +100,5 @@
 	int m,n;
 	IssmDouble* matrix=NULL;
-	
+
 	_printLine_("DoubleMatArrayParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -121,10 +121,4 @@
 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){
@@ -136,5 +130,5 @@
 /*FUNCTION DoubleMatArrayParam::copy{{{*/
 Object* DoubleMatArrayParam::copy() {
-	
+
 	return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
 
@@ -156,5 +150,4 @@
 	int*     out_ndim_array=NULL;
 
-
 	out_M=this->M;
 	if(out_M){
@@ -187,5 +180,4 @@
 	}
 
-
 	/*Assign output pointers:*/
 	if(pout_M) *pout_M=out_M;
@@ -222,5 +214,5 @@
 	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);
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for object holding an array of serial matrices
  */
-
 
 #ifndef _DOUBLEMATARRAYPARAM_H_
@@ -23,9 +22,9 @@
 
 	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
+		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:
@@ -39,5 +38,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -59,4 +57,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp	(revision 13975)
@@ -58,5 +58,5 @@
 
 	int i,j;
-	
+
 	_printLine_("DoubleMatParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -72,10 +72,4 @@
 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){
@@ -87,5 +81,5 @@
 /*FUNCTION DoubleMatParam::copy{{{*/
 Object* DoubleMatParam::copy() {
-	
+
 	return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
 
Index: /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _DOUBLEMATPARAM_H_
@@ -23,8 +22,8 @@
 
 	protected: 
-		int enum_type;
-		IssmDouble* value;
-		int M;
-		int N;
+		int         enum_type;
+		IssmDouble *value;
+		int         M;
+		int         N;
 
 	public:
@@ -38,5 +37,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -58,4 +56,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp	(revision 13975)
@@ -53,10 +53,4 @@
 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){
@@ -68,5 +62,5 @@
 /*FUNCTION DoubleParam::copy{{{*/
 Object* DoubleParam::copy() {
-	
+
 	return new DoubleParam(this->enum_type,this->value);
 
Index: /issm/trunk/src/c/classes/objects/Params/DoubleParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _DOUBLEPARAM_H_
@@ -24,5 +23,5 @@
 	private: 
 		/*just hold 3 values for 3 vertices: */
-		int enum_type;
+		int        enum_type;
 		IssmDouble value;
 
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
Index: /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for DoubleTransientMatParam object
  */
-
 
 #ifndef _DOUBLETRANSIENTMATPARAM_H_
Index: /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp	(revision 13975)
@@ -57,5 +57,5 @@
 
 	int i;
-	
+
 	_printLine_("DoubleVecParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -69,10 +69,4 @@
 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){
@@ -84,5 +78,5 @@
 /*FUNCTION DoubleVecParam::copy{{{*/
 Object* DoubleVecParam::copy() {
-	
+
 	return new DoubleVecParam(this->enum_type,this->values,this->M);
 
Index: /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _DOUBLEVECPARAM_H_
@@ -23,7 +22,7 @@
 
 	private: 
-		int enum_type;
-		IssmDouble* values;
-		int M;
+		int         enum_type;
+		IssmDouble *values;
+		int         M;
 
 	public:
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
@@ -72,5 +71,5 @@
 		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);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/FileParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/FileParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/FileParam.cpp	(revision 13975)
@@ -56,10 +56,4 @@
 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){
@@ -71,5 +65,5 @@
 /*FUNCTION FileParam::copy{{{*/
 Object* FileParam::copy() {
-	
+
 	return new FileParam(this->enum_type,this->value);
 
Index: /issm/trunk/src/c/classes/objects/Params/FileParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/FileParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/FileParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _FILEPARAM_H_
@@ -36,5 +35,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -56,4 +54,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){*pfid=value;};
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
Index: /issm/trunk/src/c/classes/objects/Params/GenericParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/GenericParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/GenericParam.h	(revision 13975)
@@ -49,5 +49,4 @@
                 void  Echo() {DeepEcho();};
                 int   Id(){ return -1; };
-                int   MyRank() { extern int my_rank; return my_rank;} ;
                 int   ObjectEnum() {return AdolcParamEnum;};
 
@@ -80,4 +79,5 @@
                 void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Mat");}
                 void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a FILE");}
+				void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a DataSet");}
 
                 void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a bool");}
@@ -99,4 +99,3 @@
 };
 
-
 #endif /* GENERICPARAM_H_ */
Index: /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp	(revision 13975)
@@ -58,5 +58,5 @@
 
 	int i,j;
-	
+
 	_printLine_("IntMatParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -72,10 +72,4 @@
 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){
@@ -87,5 +81,5 @@
 /*FUNCTION IntMatParam::copy{{{*/
 Object* IntMatParam::copy() {
-	
+
 	return new IntMatParam(this->enum_type,this->value,this->M,this->N);
 
Index: /issm/trunk/src/c/classes/objects/Params/IntMatParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntMatParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntMatParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _INTMATPARAM_H_
@@ -38,5 +37,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -58,4 +56,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/IntParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntParam.cpp	(revision 13975)
@@ -56,10 +56,4 @@
 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){
@@ -71,5 +65,5 @@
 /*FUNCTION IntParam::copy{{{*/
 Object* IntParam::copy() {
-	
+
 	return new IntParam(this->enum_type,this->value);
 
Index: /issm/trunk/src/c/classes/objects/Params/IntParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _INTPARAM_H_
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
Index: /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp	(revision 13975)
@@ -73,5 +73,5 @@
 
 	int i;
-	
+
 	_printLine_("IntVecParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -85,10 +85,4 @@
 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){
@@ -100,5 +94,5 @@
 /*FUNCTION IntVecParam::copy{{{*/
 Object* IntVecParam::copy() {
-	
+
 	return new IntVecParam(this->enum_type,this->values,this->M);
 
Index: /issm/trunk/src/c/classes/objects/Params/IntVecParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/IntVecParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/IntVecParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _INTVECPARAM_H_
@@ -38,5 +37,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -58,4 +56,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
@@ -73,5 +72,5 @@
 		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);
 		/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp	(revision 13975)
@@ -55,5 +55,4 @@
 void MatrixParam::DeepEcho(void){
 
-	int i;
 	_printLine_("MatrixParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -63,10 +62,4 @@
 /*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{{{*/
@@ -79,5 +72,5 @@
 /*FUNCTION MatrixParam::copy{{{*/
 Object* MatrixParam::copy() {
-	
+
 	return new MatrixParam(this->enum_type,this->value);
 
@@ -103,8 +96,8 @@
 /*FUNCTION MatrixParam::SetValue{{{*/
 void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
-	
+
 	/*avoid leak: */
 	xdelete(&value);
-	
+
 	/*copy: */
 	value=matrix->Duplicate();
Index: /issm/trunk/src/c/classes/objects/Params/MatrixParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/MatrixParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/MatrixParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for MatrixParam object
  */
-
 
 #ifndef _MATRIXPARAM_H_
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** poutput);
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/Param.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/Param.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/Param.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief abstract class for Param object
  */ 
-
 
 #ifndef _PARAM_H_
@@ -41,5 +40,6 @@
 		virtual void  GetParameterValue(Matrix<IssmDouble>** pmat)=0;
 		virtual void  GetParameterValue(FILE** pfid)=0;
-		
+		virtual void  GetParameterValue(DataSet** pdataset)=0;
+
 		virtual void  SetValue(bool boolean)=0;
 		virtual void  SetValue(int integer)=0;
Index: /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp	(revision 13975)
@@ -46,12 +46,12 @@
 	}
 	else value=NULL;
-	
+
 }
 /*}}}*/
 /*FUNCTION StringArrayParam::~StringArrayParam(){{{*/
 StringArrayParam::~StringArrayParam(){
-		
+
 	int i;
-	
+
 	char* string=NULL;
 	for(i=0;i<this->numstrings;i++){
@@ -86,10 +86,4 @@
 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){
@@ -101,5 +95,5 @@
 /*FUNCTION StringArrayParam::copy{{{*/
 Object* StringArrayParam::copy() {
-	
+
 	return new StringArrayParam(this->enum_type,this->value,this->numstrings);
 
@@ -110,5 +104,5 @@
 /*FUNCTION StringArrayParam::GetParameterValue{{{*/
 void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){
-	
+
 	int   i;
 	char** outstrings=NULL;
@@ -146,5 +140,5 @@
 /*FUNCTION StringArrayParam::SetValue{{{*/
 void  StringArrayParam::SetValue(char** stringarray,int M){
-	
+
 	int   i;
 	char *string     = NULL;
Index: /issm/trunk/src/c/classes/objects/Params/StringArrayParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringArrayParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/StringArrayParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _STRINGARRAYPARAM_H_
@@ -28,5 +27,4 @@
 		int      numstrings;
 
-
 	public:
 		/*StringArrayParam constructors, destructors: {{{*/
@@ -39,5 +37,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -59,4 +56,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/StringParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/StringParam.cpp	(revision 13975)
@@ -33,5 +33,4 @@
 	xMemCpy<char>(value,in_value,(strlen(in_value)+1));
 
-	
 }
 /*}}}*/
@@ -58,10 +57,4 @@
 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){
@@ -73,5 +66,5 @@
 /*FUNCTION StringParam::copy{{{*/
 Object* StringParam::copy() {
-	
+
 	return new StringParam(this->enum_type,this->value);
 
@@ -82,5 +75,5 @@
 /*FUNCTION StringParam::GetParameterValue{{{*/
 void  StringParam::GetParameterValue(char** pstring){
-	
+
 	char* outstring=NULL;
 	int   stringsize;
@@ -102,7 +95,7 @@
 /*FUNCTION StringParam::SetValue{{{*/
 void  StringParam::SetValue(char* string){
-	
+
 	int   stringsize;
-	
+
 	/*avoid leak: */
 	xDelete<char>(this->value);
Index: /issm/trunk/src/c/classes/objects/Params/StringParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/StringParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/StringParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _STRINGPARAM_H_
@@ -24,6 +23,6 @@
 	private: 
 		/*just hold 3 values for 3 vertices: */
-		int enum_type;
-		char* value;
+		int   enum_type;
+		char *value;
 
 	public:
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/TransientParam.cpp	(revision 13975)
@@ -61,10 +61,8 @@
 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++){
+	for(int i=0;i<this->N;i++){
 		_printLine_(   "time: " << this->timesteps[i] << " value: " << this->values[i]);
 	}
@@ -73,10 +71,4 @@
 /*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{{{*/
@@ -89,5 +81,5 @@
 /*FUNCTION TransientParam::copy{{{*/
 Object* TransientParam::copy() {
-	
+
 	return new TransientParam(this->enum_type,this->values,this->timesteps,this->N);
 
Index: /issm/trunk/src/c/classes/objects/Params/TransientParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/TransientParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/TransientParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _TRANSIENTPARAM_H_
@@ -23,8 +22,8 @@
 
 	protected: 
-		int enum_type;
-		int N;
-		IssmDouble* values;
-		IssmDouble* timesteps;
+		int         enum_type;
+		int         N;
+		IssmDouble *values;
+		IssmDouble *timesteps;
 
 	public:
@@ -38,5 +37,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -58,4 +56,5 @@
 		void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
 		void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/VectorParam.cpp	(revision 13975)
@@ -57,5 +57,4 @@
 void VectorParam::DeepEcho(void){
 
-	int i;
 	_printLine_("VectorParam:");
 	_printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
@@ -65,10 +64,4 @@
 /*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{{{*/
@@ -81,5 +74,5 @@
 /*FUNCTION VectorParam::copy{{{*/
 Object* VectorParam::copy() {
-	
+
 	return new VectorParam(this->enum_type,this->value);
 
@@ -109,5 +102,5 @@
 	/*avoid leak: */
 	xdelete(&value);
-	
+
 	/*copy: */
 	value=vector->Duplicate();
Index: /issm/trunk/src/c/classes/objects/Params/VectorParam.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Params/VectorParam.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Params/VectorParam.h	(revision 13975)
@@ -2,5 +2,4 @@
  *  \brief: header file for triavertexinput object
  */
-
 
 #ifndef _VECTORPARAM_H_
@@ -37,5 +36,4 @@
 		void  DeepEcho();
 		int   Id(); 
-		int   MyRank();
 		int   ObjectEnum();
 		Object* copy();
@@ -57,4 +55,5 @@
 		void  GetParameterValue(Vector<IssmDouble>** poutput);
 		void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
+		void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
 
 		void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
Index: /issm/trunk/src/c/classes/objects/Profiler.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Profiler.cpp	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/Profiler.cpp	(revision 13975)
@@ -0,0 +1,174 @@
+/*!\file Profiler.c
+ * \brief: implementation of the Profiler object
+ */
+
+/*Include files: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Profiler.h"
+/*}}}*/
+
+/*Profiler constructors and destructors:*/
+/*FUNCTION Profiler::Profiler() default constructor {{{*/
+Profiler::Profiler(){
+		 this->time=new Parameters();
+		 this->flops=new Parameters();
+		 this->memory=new Parameters();
+}
+/*}}}*/
+/*FUNCTION Profiler::~Profiler(){{{*/
+Profiler::~Profiler(){
+	delete time;
+	delete flops;
+	delete memory;
+}
+/*}}}*/
+
+/*Object virtual functions definitions:*/
+/*FUNCTION Profiler::Echo{{{*/
+void Profiler::Echo(void){
+
+	_printLine_("Profiler:");
+	_printLine_("   time tags: ");
+	this->time->Echo();
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeepEcho{{{*/
+void Profiler::DeepEcho(void){
+
+	_printLine_("Profiler:");
+	_printLine_("   time tags: ");
+	this->time->DeepEcho();
+
+}
+/*}}}*/
+/*FUNCTION Profiler::Id{{{*/
+int    Profiler::Id(void){ return -1; }
+/*}}}*/
+/*FUNCTION Profiler::ObjectEnum{{{*/
+int Profiler::ObjectEnum(void){
+
+	return ProfilerEnum;
+
+}
+/*}}}*/
+
+/*Profiler routines:*/
+/*FUNCTION Profiler::Tag {{{*/
+void  Profiler::Tag(int tagenum,bool dontmpisync){
+
+	IssmDouble t;
+	IssmDouble f;
+	IssmDouble m;
+
+	/*If mpisync requested, make sure all the cpus are at the same point 
+	 *in the execution: */
+	if(!dontmpisync){
+		#ifdef _HAVE_MPI_
+		MPI_Barrier(IssmComm::GetComm()); 
+		#endif
+	}
+
+	/*Capture time: */
+	#ifdef _HAVE_MPI_
+	t=MPI_Wtime();
+	#else
+	t=(IssmPDouble)clock();
+	#endif
+
+	/*Capture flops: */
+	#ifdef _HAVE_PETSC_
+		PetscGetFlops(&f);
+		PetscMemoryGetCurrentUsage(&m);
+	#else
+		/*do nothing for now:*/
+	#endif
+
+	/*Plug into this->time: */
+	this->time->AddObject(new DoubleParam(tagenum,t));
+	this->flops->AddObject(new DoubleParam(tagenum,f));
+	this->memory->AddObject(new DoubleParam(tagenum,m));
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTime {{{*/
+IssmDouble  Profiler::DeltaTime(int inittag, int finaltag){
+
+	IssmDouble init, final;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&final,finaltag);
+
+	#ifdef _HAVE_MPI_
+	return final-init;
+	#else
+	return (final-init)/CLOCKS_PER_SEC;
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaFlops {{{*/
+IssmDouble  Profiler::DeltaFlops(int inittag, int finaltag){
+
+	IssmDouble init, final;
+	this->flops->FindParam(&init,inittag);
+	this->flops->FindParam(&final,finaltag);
+
+	return final-init;
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModHour {{{*/
+int Profiler::DeltaTimeModHour(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int((reCast<int,IssmDouble>(finish-init))/3600);
+	#else
+	return int((reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC/3600);
+	#endif
+
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModMin {{{*/
+int Profiler::DeltaTimeModMin(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int(int(reCast<int,IssmDouble>(finish-init))%3600/60);
+	#else
+	return int(int(reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC%3600/60);
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::DeltaTimeModSec {{{*/
+int Profiler::DeltaTimeModSec(int inittag, int finishtag){
+
+	IssmDouble init, finish;
+	this->time->FindParam(&init,inittag);
+	this->time->FindParam(&finish,finishtag);
+
+	#ifdef _HAVE_MPI_
+	return int(reCast<int,IssmDouble>(finish-init))%60;
+	#else
+	return int(reCast<int,IssmDouble>(finish-init))/CLOCKS_PER_SEC%60;
+	#endif
+}
+/*}}}*/
+/*FUNCTION Profiler::Memory {{{*/
+IssmDouble  Profiler::Memory(int tag){
+
+	IssmDouble m;
+	this->memory->FindParam(&m,tag);
+
+	return m;
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Profiler.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Profiler.h	(revision 13975)
+++ /issm/trunk/src/c/classes/objects/Profiler.h	(revision 13975)
@@ -0,0 +1,57 @@
+/*!\file Profiler.h
+ * \brief: header file for node object
+ */
+
+#ifndef _PROFILER_H_
+#define _PROFILER_H_
+
+/*Headers:*/
+/*{{{*/
+#include "./Object.h"
+#include "../../shared/shared.h"
+/*}}}*/
+
+class DataSet;
+class Parameters;
+
+enum ProfilerEnums {
+	Start,
+	StartInit,
+	FinishInit,
+	StartCore,
+	FinishCore,
+	StartAdCore,
+	FinishAdCore,
+	Finish
+};
+
+class Profiler: public Object{
+
+	public: 
+		Parameters*  time;
+		Parameters*  flops;
+		Parameters*  memory;
+
+		/*Profiler constructors, destructors {{{*/
+		Profiler();
+		~Profiler();
+		/*}}}*/
+		/*Object virtual functions definitions:{{{ */
+		void    Echo();
+		void    DeepEcho();
+		int     Id();
+		int     ObjectEnum();
+		Object *copy()        {_error_("Not implemented yet"); };
+		/*}}}*/
+		/*Profiler routines {{{*/
+		void    Tag(int tagenum,bool dontmpisync=false);
+		IssmDouble  Memory(int tag);
+		IssmDouble  DeltaTime(int inittag, int finaltag);
+		IssmDouble  DeltaFlops(int inittag, int finaltag);
+		int     DeltaTimeModHour(int inittag, int finaltag);
+		int     DeltaTimeModMin(int inittag, int finaltag);
+		int     DeltaTimeModSec(int inittag, int finaltag);
+		/*}}}*/
+};
+
+#endif  /* _PROFILER_H_ */
Index: /issm/trunk/src/c/classes/objects/Segment.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Segment.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Segment.h	(revision 13975)
@@ -15,5 +15,5 @@
 
 	public:
-		int eid;
+		int        eid;
 		doubletype x1;
 		doubletype y1;
@@ -21,13 +21,12 @@
 		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;
+			this->eid = UNDEF;
+			this->x1  = UNDEF;
+			this->y1  = UNDEF;
+			this->x2  = UNDEF;
+			this->y2  = UNDEF;
 		}
 		/*}}}*/
@@ -35,9 +34,9 @@
 		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;
+			this->eid = segment_eid;
+			this->x1  = segment_x1;
+			this->y1  = segment_y1;
+			this->x2  = segment_x2;
+			this->y2  = segment_y2;
 
 		}
@@ -67,11 +66,4 @@
 		int    Id(void){ return eid; }
 		/*}}}*/
-		/*FUNCTION MyRank{{{*/
-		int    MyRank(void){ 
-			extern int my_rank;
-
-			return my_rank; 
-		}
-		/*}}}*/
 		/*FUNCTION ObjectEnum{{{*/
 		int ObjectEnum(void){
@@ -84,7 +76,5 @@
 		Object* copy() {
 			return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
-
 		}
-
 		/*}}}*/
 
Index: /issm/trunk/src/c/classes/objects/Vertex.cpp
===================================================================
--- /issm/trunk/src/c/classes/objects/Vertex.cpp	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Vertex.cpp	(revision 13975)
@@ -49,4 +49,5 @@
 	this->id=vertex_id;
 	this->sid=vertex_sid;
+	this->pid=UNDEF;
 	this->x=vertex_x;
 	this->y=vertex_y;
@@ -54,5 +55,4 @@
 	this->sigma=vertex_sigma;
 	this->connectivity=vertex_connectivity;
-	this->dof=UNDEF;
 
 	return;
@@ -67,4 +67,5 @@
 	_printLine_("   id: " << id);
 	_printLine_("   sid: " << sid);
+	_printLine_("   pid: " << pid);
 	_printLine_("   x: " << x);
 	_printLine_("   y: " << y);
@@ -72,5 +73,4 @@
 	_printLine_("   sigma: " << sigma);
 	_printLine_("   connectivity: " << connectivity);
-	_printLine_("   dof: " << dof);
 	_printLine_("   clone: " << clone);
 
@@ -86,10 +86,4 @@
 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){
@@ -103,88 +97,4 @@
 
 	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; 	
-	}
 
 }
@@ -209,10 +119,77 @@
 	/*sigma remains constant. z=bed+sigma*thickness*/
 	oldz = this->z;
-	newz = bed[this->dof]+sigma*thickness[this->dof];
+	newz = bed[this->pid]+sigma*thickness[this->pid];
 	velz = (newz-oldz)/dt;
 	this->z = newz;
 
 	/*put vz in vector*/
-	vz->SetValue(this->dof,velz,INS_VAL);
+	vz->SetValue(this->pid,velz,INS_VAL);
 }
 /*}}}*/
+/*FUNCTION Vertex::DistributePids{{{*/
+void  Vertex::DistributePids(int* ppidcount){
+
+	/*retrieve current pid*/
+	int pidcount=*ppidcount;
+
+	/*This vertex is a clone! Don't distribute pids, it will get them from another cpu!*/
+	if(this->clone) return;
+
+	/*This vertex should distribute its pid*/
+	this->pid=pidcount;
+	pidcount++;
+
+	/*Assign output pointers: */
+	*ppidcount=pidcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::OffsetPids{{{*/
+void  Vertex::OffsetPids(int pidcount){
+
+	/*This vertex is a clone, don't offset the pids*/
+	if(this->clone) return;
+
+	/*This vertex should offset his pid, go ahead: */
+	this->pid+=pidcount;
+}
+/*}}}*/
+/*FUNCTION Vertex::ShowTruePids{{{*/
+void  Vertex::ShowTruePids(int* truepids){
+
+	/*Are we a clone? : */
+	if(this->clone)return;
+
+	/*Ok, we are not a clone, just plug our pid into truepids: */
+	truepids[this->sid]=this->pid;
+}
+/*}}}*/
+/*FUNCTION Vertex::UpdateClonePids{{{*/
+void  Vertex::UpdateClonePids(int* alltruepids){
+
+	/*If we are not a clone, don't update, we already have pids: */
+	if(!this->clone)return;
+
+	/*Ok, we are a clone node, but we did not create the pid for this vertex 
+	 * Therefore, our pid is garbage right now. Go pick it up in the alltruepids: */
+	this->pid=alltruepids[this->sid];
+}
+/*}}}*/
+/*FUNCTION Vertex::SetClone {{{*/
+void  Vertex::SetClone(int* minranks){
+
+	int my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if (minranks[this->sid]==my_rank){
+		this->clone=false;
+	}
+	else{
+		/*!there is a cpu with lower rank that has the same vertex, 
+		therefore, I am a clone*/
+		this->clone=true;
+	}
+
+}
+/*}}}*/
Index: /issm/trunk/src/c/classes/objects/Vertex.h
===================================================================
--- /issm/trunk/src/c/classes/objects/Vertex.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/Vertex.h	(revision 13975)
@@ -9,29 +9,24 @@
 /*{{{*/
 #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"
-
+template <class doubletype> class Vector;
+class Parameters;
+class IoModel;
 /*}}}*/
-
 
 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.
+		bool       clone;
+		int        id;           // random index
+		int        sid;          // "serial" id (rank of this vertex if the dataset was on 1 cpu)
+		int        pid;          // "parallel" id
 		IssmDouble x;
 		IssmDouble y;
 		IssmDouble z;
-		IssmDouble sigma;          //sigma coordinate: (z-bed)/thickness
-		int    connectivity;   //number of vertices connected to this vertex
-
-		/*dof management: */
-		int    clone;
-		int    dof; //dof to recover values in a vertex indexed vector
+		IssmDouble sigma;        //sigma coordinate: (z-bed)/thickness
+		int        connectivity; //number of vertices connected to this vertex
 
 		/*Vertex constructors, destructors {{{*/
@@ -46,20 +41,16 @@
 		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: {{{*/
+		/*Vertex management:*/ 
 		int   Sid(void); 
 		int   Connectivity(void); 
 		void  UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
-		/*}}}*/
+		void  DistributePids(int* ppidcount);
+		void  OffsetPids(int pidcount);
+		void  ShowTruePids(int* borderpids);
+		void  UpdateClonePids(int* allborderpids);
+		void  SetClone(int* minranks);
 };
 #endif  /* _VERTEX_H */
Index: /issm/trunk/src/c/classes/objects/objects.h
===================================================================
--- /issm/trunk/src/c/classes/objects/objects.h	(revision 13974)
+++ /issm/trunk/src/c/classes/objects/objects.h	(revision 13975)
@@ -13,4 +13,7 @@
 #include "./Vertex.h"
 #include "./Node.h"
+#include "./Profiler.h"
+#include "./DependentObject.h"
+#include "./IndependentObject.h"
 #include "./Segment.h"
 
@@ -119,4 +122,5 @@
 #include "./Params/StringParam.h"
 #include "./Params/TransientParam.h"
+#include "./Params/DataSetParam.h"
 
 #endif
Index: /issm/trunk/src/c/include/globals.h
===================================================================
--- /issm/trunk/src/c/include/globals.h	(revision 13974)
+++ /issm/trunk/src/c/include/globals.h	(revision 13975)
@@ -6,6 +6,8 @@
 #define GLOBALS_H_
 
-int my_rank=0;
-int num_procs=1;
+#include "./types.h"
+#include "../classes/IssmComm.h"
+
+COMM IssmComm::comm;
 
 #endif
Index: /issm/trunk/src/c/include/macros.h
===================================================================
--- /issm/trunk/src/c/include/macros.h	(revision 13974)
+++ /issm/trunk/src/c/include/macros.h	(revision 13975)
@@ -23,5 +23,5 @@
 #define _printf_(flag,...) do{if(flag) PrintfFunction(__VA_ARGS__);}while(0)
 /*}}}*/
-/* _error2_ {{{*/
+/* _error_ {{{*/
 /*new Error exception macro*/
 #ifdef _INTEL_WIN_
@@ -71,24 +71,25 @@
 #endif
 /*}}}*/
-/* ISSMBOOT/ISSMEND {{{*/
+/* ExceptionTrapBegin/ExceptionTrapEnd {{{*/
 
 /*The following macros hide the error exception handling in a matlab module. Just put 
- * ISSMBOOT(); and ISSMEND(); at the beginning and end of a module, and c++ exceptions 
+ * ExceptionTrapBegin(); and ExceptionTrapEnd(); at the beginning and end of a module, and c++ exceptions 
  * will be trapped. Really nifty!*/
 
-#define ISSMBOOT(); \
+#define ExceptionTrapBegin(); \
 	try{
 
-#define ISSMEND(); }\
+#define ExceptionTrapEnd(); }\
 	catch(ErrorException &exception){\
-		exception.Report(); \
-		return 1;\
+		exception.Report();\
+		return 0;\
 	}\
 	catch (exception& e) {\
 		_printf_(true,"Standard exception: %s\n",e.what());\
-		return 1;\
+		return 0;\
 	}\
 	catch(...){\
 		_printf_(true,"An unexpected error occurred");\
+		return 0;\
 	}
 /*}}}*/
Index: /issm/trunk/src/c/include/typedefs.h
===================================================================
--- /issm/trunk/src/c/include/typedefs.h	(revision 13974)
+++ /issm/trunk/src/c/include/typedefs.h	(revision 13975)
@@ -36,5 +36,5 @@
 #define INFINITY (DBL_MAX+DBL_MAX)
 #define NAN (INFINITY-INFINITY)
-	
+
 #endif
 
Index: /issm/trunk/src/c/include/types.h
===================================================================
--- /issm/trunk/src/c/include/types.h	(revision 13974)
+++ /issm/trunk/src/c/include/types.h	(revision 13975)
@@ -5,5 +5,4 @@
 #ifndef _TYPES_H_
 #define  _TYPES_H_
-
 
 #ifdef HAVE_CONFIG_H
@@ -27,5 +26,5 @@
 #endif  
 
-#ifdef _HAVE_ADOLC_
+#if defined(_HAVE_ADOLC_) &&  !defined(_WRAPPERS_)
 #include "adolc/adolc.h"
 // for active variables
@@ -40,5 +39,11 @@
 #endif
 
-typedef bool IssmBool;
+/*Define communicator: */
+#ifdef _HAVE_MPI_
+#include <mpi.h>
+typedef MPI_Comm COMM;
+#else
+typedef int COMM;
+#endif
 
 #endif //ifndef _TYPES_H_
Index: /issm/trunk/src/c/io/Disk/WriteLockFile.cpp
===================================================================
--- /issm/trunk/src/c/io/Disk/WriteLockFile.cpp	(revision 13975)
+++ /issm/trunk/src/c/io/Disk/WriteLockFile.cpp	(revision 13975)
@@ -0,0 +1,25 @@
+/*!\file:  WriteLockFile.cpp
+ * \brief
+ */ 
+#include <stdio.h>
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+
+void WriteLockFile(char* filename){
+
+	/*recover my_rank:*/
+	int my_rank=IssmComm::GetRank();
+
+	/* output: */
+	FILE* fid=NULL;
+
+	/* Open lock file and write 1 into it: */
+	if(my_rank==0){
+		fid=fopen(filename,"w");
+		if(fid==NULL) _error_("error message: could not open lock file " << filename);
+
+		/*Close file: */
+		if(fclose(fid)!=0) _error_("could not close lock file " << filename);
+	}
+
+}	
Index: /issm/trunk/src/c/io/Disk/diskio.h
===================================================================
--- /issm/trunk/src/c/io/Disk/diskio.h	(revision 13974)
+++ /issm/trunk/src/c/io/Disk/diskio.h	(revision 13975)
@@ -10,4 +10,5 @@
 FILE* pfopen(char* filename,const char* format);
 void  pfclose(FILE* fid,char* filename);
+void WriteLockFile(char* filename);
 
 #endif	/* _IO_H_ */
Index: /issm/trunk/src/c/io/Disk/pfclose.cpp
===================================================================
--- /issm/trunk/src/c/io/Disk/pfclose.cpp	(revision 13974)
+++ /issm/trunk/src/c/io/Disk/pfclose.cpp	(revision 13975)
@@ -16,5 +16,4 @@
 
 	/*Close file handle: */
-	extern int my_rank;
 	_assert_(fid);
 	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 13974)
+++ /issm/trunk/src/c/io/Disk/pfopen.cpp	(revision 13975)
@@ -16,6 +16,5 @@
 
 	FILE* fid=NULL;
-	extern int my_rank;
-	
+
 	/*Open handle to data on disk: */
 	fid=fopen(filename,format);
@@ -24,3 +23,2 @@
 	return fid;
 }
-
Index: /issm/trunk/src/c/io/PrintfFunction.cpp
===================================================================
--- /issm/trunk/src/c/io/PrintfFunction.cpp	(revision 13974)
+++ /issm/trunk/src/c/io/PrintfFunction.cpp	(revision 13975)
@@ -15,10 +15,10 @@
 	char *buffer = NULL;
 	int   n,size = 100;
-	int         string_size;
-	extern int  my_rank;
-	extern int  num_procs;
-                                                                                                                                                                                                     
+	int   my_rank;
 	//variable list of arguments
 	va_list args;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	while(true){
@@ -52,5 +52,9 @@
 }
 int PrintfFunction(const string & message){
-	extern int  my_rank;
+	int  my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	if(my_rank==0){
 		printf("%s\n",message.c_str());
@@ -59,5 +63,9 @@
 }
 int PrintfFunction2(const string & message){
-	extern int  my_rank;
+	int  my_rank;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	if(my_rank==0){
 		printf("%s",message.c_str());
Index: sm/trunk/src/c/issm-binding.h
===================================================================
--- /issm/trunk/src/c/issm-binding.h	(revision 13974)
+++ 	(revision )
@@ -1,18 +1,0 @@
-#ifndef _ISSM_BINDING_H_
-#define _ISSM_BINDING_H_
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#ifdef  _HAVE_MATLAB_MODULES_
-#include "./matlab/matlab-binding.h"
-#endif
-
-#ifdef  _HAVE_PYTHON_MODULES_
-#include "./python/python-binding.h"
-#endif
-
-#endif
Index: /issm/trunk/src/c/issm.h
===================================================================
--- /issm/trunk/src/c/issm.h	(revision 13974)
+++ /issm/trunk/src/c/issm.h	(revision 13975)
@@ -12,4 +12,5 @@
 #endif
 
+#include "./include/globals.h" //only include this header file once!
 #include "./include/include.h"
 #include "./shared/shared.h"
Index: /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 
 int AverageFilterx(double** pimageout,double* image, int lines,int samps,int smooth){
-	
+
 	double      temp;
 	int         numvalues;
Index: /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.h
===================================================================
--- /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.h	(revision 13975)
@@ -11,5 +11,4 @@
 /* local prototypes: */
 int AverageFilterx(double** pimageout,double* imagein, int lines,int samp,int smooth);
-	
+
 #endif /* AVERAGEFILTERX_H */
-
Index: /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp	(revision 13975)
@@ -18,10 +18,7 @@
 #include "../modules.h"
 
-			
 void AverageOntoPartitionx(double** paverage, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response){
 
-	int     i,j,k;
 	int     dummy;
-
 	int     npart;
 	double *qmu_part  = NULL;
@@ -49,6 +46,6 @@
 
 	/*loop on each element, and add contribution of the element to the partition (surface weighted average): */
-	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+	for(int i=0;i<elements->Size();i++){
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->AverageOntoPartition(partition_contributions,partition_areas,vertex_response,qmu_part);
 	}
Index: /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Bamgx/Bamgx.cpp	(revision 13975)
@@ -20,6 +20,6 @@
 
 	/*intermediary*/
+	int i;
 	int noerr=1;
-	int i,j,num;
 	double costheta=2;
 	double hminaniso=1e-100; 
Index: /issm/trunk/src/c/modules/Chacox/Chacox.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/Chacox.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Chacox/Chacox.cpp	(revision 13975)
@@ -21,6 +21,5 @@
 {
 	#ifdef _HAVE_CHACO_ //only works if Chaco library has been compiled in.
-	
-	
+
 	extern int Using_Main;	/* is main routine being called? */
 	extern char *PARAMS_FILENAME;	/* name of file with parameter updates */
@@ -62,6 +61,4 @@
 	int i,tvwgt;
 	double tgoal;
-
-
 
 	if (DEBUG_TRACE > 0) {
@@ -187,7 +184,6 @@
 		_printLine_("<Leaving main>");
 	}
-	
+
 	return(0);
-
 
 	#else //ifdef _HAVE_CHACO_
Index: /issm/trunk/src/c/modules/Chacox/Chacox.h
===================================================================
--- /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Chacox/Chacox.h	(revision 13975)
@@ -44,4 +44,3 @@
 #define __FUNCT__  "Chacox"
 
-
 #endif  /* _CHACOX_H */
Index: /issm/trunk/src/c/modules/Chacox/chaco_seconds.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/chaco_seconds.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Chacox/chaco_seconds.cpp	(revision 13975)
@@ -8,8 +8,6 @@
 #endif
 
+double chaco_seconds(void){
 
-
-double chaco_seconds(void){
-    
 	double    curtime;
 
@@ -22,5 +20,5 @@
 	 *is defined in the <sys/time.h> and <sys/resource.h> header files. Leaving it 
 	 *for reference in case we have a problem here in the future*/
- 
+
     getrusage(RUSAGE_SELF, &rusage);
     curtime = ((rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec) +
Index: /issm/trunk/src/c/modules/Chacox/input_parse.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/input_parse.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Chacox/input_parse.cpp	(revision 13975)
@@ -4,5 +4,4 @@
 
 #include "./Chacox.h"
-
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/c/modules/Chacox/user_params.cpp
===================================================================
--- /issm/trunk/src/c/modules/Chacox/user_params.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Chacox/user_params.cpp	(revision 13975)
@@ -14,5 +14,4 @@
 #endif
 
-
 #ifdef _HAVE_CHACO_ //only works if dakota library has been compiled in.
 
@@ -21,5 +20,4 @@
 #define  TRUE  1
 #define  FALSE 0
-
 
 /* Input and ouput control parameters */
@@ -34,5 +32,4 @@
 int       PROMPT = FALSE;	 /* Prompt for input? (TRUE/FALSE) */
 int       PRINT_HEADERS = FALSE; /* Print pretty output headers (TRUE/FALSE) */
-
 
 /* Eigenvector calculation parameters */
@@ -57,5 +54,4 @@
 int       TIME_KERNELS = FALSE;	/* Time numerical kernels? (TRUE/FALSE) */
 
-
 /* Other parameters for spectral methods */
 
@@ -69,5 +65,4 @@
 int       OPT3D_NTRIES = 5;	/* # local opts to look for global min in opt3d */
 
-
 /* Kernighan--Lin/Fiduccia--Mattheyses parameters */
 
@@ -78,5 +73,4 @@
 int       KL_UNDO_LIST = TRUE;	/* Only resort changed vtxs? (TRUE/FALSE) */
 double    KL_IMBALANCE = 0.0;	/* Fractional imbalance allowed by KL */
-
 
 /* Coarsening parameters */
@@ -91,5 +85,4 @@
 int       KL_ONLY_BNDY = TRUE;	   /* Start moving vtxs on boundary? (TRUE/FALSE) */
 
-
 /* Parameters for post-processing options */
 
@@ -97,5 +90,4 @@
 int       INTERNAL_VERTICES = FALSE;	/* ... to up internal vtxs? (TRUE/FALSE) */
 int       REFINE_MAP = FALSE;		/* ... to reduce hops? (TRUE/FALSE) */
-
 
 /* Architecture and simulator parameters */
@@ -129,5 +121,4 @@
 char     *PARAMS_FILENAME = "User_Params";	/* File of parameter changes */
 
-
 /* Parameters that control debugging output */
 
@@ -151,4 +142,3 @@
 int       DEBUG_MACH_PARAMS = 0;/* Print computed machine params? (0..1) */
 
-
 #endif //ifdef _HAVE_CHACO_ 
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp	(revision 13975)
@@ -29,5 +29,5 @@
 	/*Compute basal stress for each element: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->ComputeBasalStress(sigma);
 	}
@@ -38,4 +38,4 @@
 	/*Assign output pointers: */
 	*psigma=sigma;
-	
+
 }
Index: /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _COMPUTEBASALSTRESSX_H */
-
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp	(revision 13975)
@@ -29,5 +29,5 @@
 	/*Compute basal stress for each element: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->ComputeStrainRate(eps);
 	}
@@ -38,4 +38,4 @@
 	/*Assign output pointers: */
 	*peps=eps;
-	
+
 }
Index: /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h
===================================================================
--- /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _COMPUTESTRAINRATEX_H */
-
Index: /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp	(revision 13975)
@@ -24,8 +24,8 @@
 	/*Get analysis type: */
 	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	
+
 	if(VerboseMProcessor()) _pprintLine_("      Configuring elements...");
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->Configure(elements,loads,nodes,materials,parameters);
 	}
@@ -44,5 +44,5 @@
 		}
 	}
-	
+
 	if(VerboseMProcessor()) _pprintLine_("      Configuring materials...");
 	for (i=0;i<materials->Size();i++){
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h	(revision 13975)
@@ -27,3 +27,2 @@
 
 #endif  /* _CONSTRAINTSSTATEX_H */
-
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp	(revision 13975)
@@ -13,9 +13,4 @@
 void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
 
-	int i;
-
-	extern int num_procs;
-	extern int my_rank;
-	
 	/*output: */
 	int converged=0;
@@ -46,5 +41,5 @@
 		converged=1;
 	}
-		
+
 	/*Assign output pointers: */
 	*pconverged=converged;
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h	(revision 13975)
@@ -15,3 +15,2 @@
 
 #endif  /* _CONSTRAINTSSTATEX_H */
-
Index: /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp	(revision 13975)
@@ -15,7 +15,6 @@
 int RiftIsPresent(Loads* loads,int configuration_type){
 
-
 	int i;
-	
+
 	int found=0;
 	int mpi_found=0;
@@ -33,6 +32,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
 	#endif
@@ -46,9 +45,8 @@
 	int num_unstable_constraints=0;
 	int converged=0;
-	int potential;
 
 	RiftConstrain(&num_unstable_constraints,loads,configuration_type);
 	if(num_unstable_constraints==0)converged=1;
-	
+
 	if(RiftIsFrozen(loads,configuration_type)){
 		converged=1;
@@ -69,5 +67,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Riftfront* riftfront=NULL;
@@ -77,5 +75,5 @@
 	int sum_num_unstable_constraints;
 	int num_unstable_constraints=0;	
-		
+
 	/*Enforce constraints: */
 	for (i=0;i<loads->Size();i++){
@@ -96,9 +94,9 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
 	#endif
-	
+
 	/*Assign output pointers: */
 	*pnum_unstable_constraints=num_unstable_constraints;
@@ -110,5 +108,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Load*      load=NULL;
@@ -121,5 +119,5 @@
 
 		if (RiftfrontEnum==loads->GetEnum(i)){
-			
+
 			load=(Load*)loads->GetObjectByOffset(i);
 			if(load->InAnalysis(configuration_type)){
@@ -133,9 +131,9 @@
 		}
 	}
-	
+
 	/*Is there just one found? that would mean we have frozen! : */
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
 	#endif
@@ -148,5 +146,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Load*      load=NULL;
@@ -160,5 +158,5 @@
 			load=(Load*)loads->GetObjectByOffset(i);
 			if(load->InAnalysis(configuration_type)){
-				
+
 				riftfront=(Riftfront*)load;
 				riftfront->FreezeConstraints();
@@ -176,5 +174,5 @@
 
 	int i;
-	
+
 	Riftfront* riftfront=NULL;
 	int found=0;
@@ -196,6 +194,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
 	#endif
@@ -207,7 +205,6 @@
 int RiftIsPreStable(Loads* loads){
 
-
 	int i;
-	
+
 	Riftfront* riftfront=NULL;
 	int found=0;
@@ -229,6 +226,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
 	#endif
@@ -246,7 +243,6 @@
 void RiftSetPreStable(Loads* loads){
 
-
 	int i;
-	
+
 	Riftfront* riftfront=NULL;
 	int found=0;
@@ -268,5 +264,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Riftfront* riftfront=NULL;
@@ -275,5 +271,5 @@
 	int sum_num_unstable_constraints;
 	int num_unstable_constraints=0;	
-		
+
 	/*Enforce constraints: */
 	for (i=0;i<loads->Size();i++){
@@ -290,9 +286,9 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
 	#endif
-	
+
 	/*Assign output pointers: */
 	*pnum_unstable_constraints=num_unstable_constraints;
@@ -304,5 +300,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Riftfront* riftfront=NULL;
@@ -330,6 +326,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,IssmComm::GetComm());                
 	max_penetration=mpi_max_penetration;
 	#endif
@@ -346,5 +342,5 @@
 
 	int			i;
-	
+
 	/* generic object pointer: */
 	Riftfront* riftfront=NULL;
@@ -369,6 +365,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
 	#endif
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp	(revision 13975)
@@ -37,6 +37,6 @@
 
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());                
 	num_unstable_constraints=sum_num_unstable_constraints;
 	#endif
Index: /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp
===================================================================
--- /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp	(revision 13975)
@@ -27,8 +27,8 @@
 		}
 	}
-	
+
 	#ifdef _HAVE_MPI_
-	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());                
 	found=mpi_found;
 	#endif
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp	(revision 13975)
@@ -8,12 +8,7 @@
 #endif
 
-
 #include "./ContourToMeshx.h"
 
 int ContourToMeshx(SeqVec<double>** pin_nod,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue) {
-
-	int noerr=1;
-	int i;
-	int m,n;
 
 	/*Contour:*/
@@ -27,5 +22,4 @@
 	num=_NUMTHREADS_;
 	#endif
-
 
 	/*output: */
@@ -54,5 +48,5 @@
 	/*Take care of the case where an element interpolation has been requested: */
 	if ((strcmp(interptype,"element")==0) || (strcmp(interptype,"element and node")==0)){
-		for (n=0;n<nel;n++){
+		for(int n=0;n<nel;n++){
 			if ( (in_nod_serial[ (int)*(index+3*n+0) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+1) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+2) -1] == 1) ){
 				value=1; in_elem->SetValue(n,value,INS_VAL);
@@ -71,4 +65,4 @@
 	xDelete<double>(in_nod_serial);
 
-	return noerr;
+	return 1;
 }
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h	(revision 13975)
@@ -2,5 +2,4 @@
 	ContourToMeshx.h
 */
-
 
 #ifndef _CONTOURTOMESHX_H
@@ -22,5 +21,4 @@
 } ContourToMeshxThreadStruct;
 
-
 /* local prototypes: */
 int ContourToMeshx(SeqVec<double>** pin_nods,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue);
Index: /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 
 void* ContourToMeshxt(void* vpthread_handle){
-	
+
 	int noerr=1;
 
Index: /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp	(revision 13975)
@@ -7,5 +7,4 @@
 
 	int i;
-	int m,n;
 
 	/*Contour:*/
@@ -14,5 +13,4 @@
 	double*  xc=NULL;
 	double*  yc=NULL;
-	double   value;
 
 	/*output: */
@@ -34,5 +32,4 @@
 	/*Assign output pointers: */
 	*pflags=flags;
-	
 	return 1;
 }
@@ -40,13 +37,8 @@
 int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue){
 
-	int i;
-	int m,n;
-
 	/*Contour:*/
 	Contour<IssmPDouble>* contouri=NULL;
-	int      numnodes;
 	double*  xc=NULL;
 	double*  yc=NULL;
-	double   value;
 
 	/*output: */
@@ -56,5 +48,5 @@
 	/*Loop through all contours: */
 	if(contours){
-		for (i=0;i<contours->Size();i++){
+		for(int i=0;i<contours->Size();i++){
 			Contour<IssmPDouble>* contour=(Contour<IssmPDouble>*)contours->GetObjectByOffset(i);
 			IsInPoly(flags,contour->x,contour->y,contour->nods,x,y,0,nods,edgevalue);
Index: /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp	(revision 13975)
@@ -16,5 +16,4 @@
 	IssmDouble *scalar_list = NULL;
 	IssmDouble  scalar;
-
 
 	/*Retrieve some parameters*/
Index: /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp	(revision 13975)
@@ -12,8 +12,5 @@
 void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type){
 
-	int i;
-	
-	/*intermediary: */
-	int  numberofdofs;
+	bool  oldalloc  = false;
 
 	/*output: */
@@ -21,12 +18,16 @@
 
 	/*figure out how many dofs we have: */
-	numberofdofs=nodes->NumberOfDofs(configuration_type,SsetEnum);
+	int ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
+	int slocalsize = nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
 
 	/*allocate:*/
-	ys=new Vector<IssmDouble>(numberofdofs);
+	if(oldalloc)
+	 ys=new Vector<IssmDouble>(ssize);
+	else
+	 ys=new Vector<IssmDouble>(slocalsize,ssize);
 
 	/*go through all nodes, and for the ones corresponding to this configuration_type, fill the 
 	 * constraints vector with the constraint values: */
-	for (i=0;i<nodes->Size();i++){
+	for(int i=0;i<nodes->Size();i++){
 		Node* node=(Node*)nodes->GetObjectByOffset(i);
 		if (node->InAnalysis(configuration_type)){
Index: /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp	(revision 13975)
@@ -15,8 +15,8 @@
   int    i;
   Element* element = NULL;
- 
+
   /*Compute temperature and precipitation fields: */
   for(i=0;i<elements->Size();i++){
-    element=(Element*)elements->GetObjectByOffset(i);
+    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     element->Delta18oParameterization();
   }  
Index: /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->DragCoefficientAbsGradient(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp	(revision 13975)
@@ -41,5 +41,5 @@
 	 * Once we get the neighbouring elements, figure out if they share a segment with the current element. If so, 
 	 * plug them in the connectivity, unless they are already there.: */
-	
+
 	for(n=0;n<nel;n++){
 
@@ -47,5 +47,5 @@
 
 		for(i=0;i<3;i++){
-		
+
 			node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
 			index=node-1;
@@ -58,5 +58,5 @@
 				connectedelement=*(nodeconnectivity+width*index+j);
 				connectedelementindex=(int)(connectedelement-1); //go from matlab indexing to c indexing.
-				
+
 				if(hascommondedge(elements+n*3+0,elements+connectedelementindex*3+0)){
 					/*Ok, this connected element has a commond edge  with element, plug it into elementconnectivity, unless 
@@ -80,5 +80,4 @@
 	*pelementconnectivity=elementconnectivity;
 }
-				
 
 int hascommondedge(double* element1,double* element2){
Index: /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.h
===================================================================
--- /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.h	(revision 13975)
@@ -10,3 +10,2 @@
 
 #endif  /* _ELEMENTCONNECTIVITYX_H */
-
Index: /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp
===================================================================
--- /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp	(revision 13975)
@@ -18,11 +18,23 @@
 
 		case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
-		case AutodiffDependentsEnum : return "AutodiffDependents";
 		case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
-		case AutodiffIndependentsEnum : return "AutodiffIndependents";
+		case AutodiffNumDependentObjectsEnum : return "AutodiffNumDependentObjects";
+		case AutodiffDependentObjectNamesEnum : return "AutodiffDependentObjectNames";
+		case AutodiffDependentObjectTypesEnum : return "AutodiffDependentObjectTypes";
+		case AutodiffDependentObjectIndicesEnum : return "AutodiffDependentObjectIndices";
+		case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
 		case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
+		case AutodiffNumIndependentObjectsEnum : return "AutodiffNumIndependentObjects";
+		case AutodiffIndependentObjectNamesEnum : return "AutodiffIndependentObjectNames";
+		case AutodiffIndependentObjectTypesEnum : return "AutodiffIndependentObjectTypes";
+		case AutodiffIndependentObjectsEnum : return "AutodiffIndependentObjects";
 		case AutodiffJacobianEnum : return "AutodiffJacobian";
 		case AutodiffXpEnum : return "AutodiffXp";
-		case AutodiffFosForwardOutputEnum : return "AutodiffFosForwardOutput";
+		case AutodiffDriverEnum : return "AutodiffDriver";
+		case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
+		case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
+		case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
+		case AutodiffMassFluxSegmentsPresentEnum : return "AutodiffMassFluxSegmentsPresent";
+		case AutodiffKeepEnum : return "AutodiffKeep";
 		case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
 		case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
@@ -36,4 +48,5 @@
 		case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
 		case ConstantsYtsEnum : return "ConstantsYts";
+		case DependentObjectEnum : return "DependentObject";
 		case DiagnosticAbstolEnum : return "DiagnosticAbstol";
 		case DiagnosticIcefrontEnum : return "DiagnosticIcefront";
@@ -75,4 +88,5 @@
 		case HydrologySpcwatercolumnEnum : return "HydrologySpcwatercolumn";
 		case HydrologyStabilizationEnum : return "HydrologyStabilization";
+		case IndependentObjectEnum : return "IndependentObject";
 		case InversionControlParametersEnum : return "InversionControlParameters";
 		case InversionCostFunctionEnum : return "InversionCostFunction";
@@ -148,6 +162,10 @@
 		case PrognosticStabilizationEnum : return "PrognosticStabilization";
 		case PrognosticVertexPairingEnum : return "PrognosticVertexPairing";
+		case PrognosticNumRequestedOutputsEnum : return "PrognosticNumRequestedOutputs";
+		case PrognosticRequestedOutputsEnum : return "PrognosticRequestedOutputs";
 		case QmuIsdakotaEnum : return "QmuIsdakota";
-		case QmuMassFluxSegmentsEnum : return "QmuMassFluxSegments";
+		case MassFluxSegmentsEnum : return "MassFluxSegments";
+		case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
+		case QmuMassFluxSegmentsPresentEnum : return "QmuMassFluxSegmentsPresent";
 		case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
 		case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
@@ -184,4 +202,6 @@
 		case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
 		case SurfaceforcingsHcEnum : return "SurfaceforcingsHc";
+		case SurfaceforcingsHrefEnum : return "SurfaceforcingsHref";
+		case SurfaceforcingsSmbrefEnum : return "SurfaceforcingsSmbref";
 		case SurfaceforcingsSmbPosMaxEnum : return "SurfaceforcingsSmbPosMax";
 		case SurfaceforcingsSmbPosMinEnum : return "SurfaceforcingsSmbPosMin";
@@ -270,4 +290,5 @@
 		case DofIndexingEnum : return "DofIndexing";
 		case DoubleInputEnum : return "DoubleInput";
+		case DataSetParamEnum : return "DataSetParam";
 		case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
 		case DoubleMatParamEnum : return "DoubleMatParam";
@@ -299,4 +320,5 @@
 		case PentaEnum : return "Penta";
 		case PentaP1InputEnum : return "PentaP1Input";
+		case ProfilerEnum : return "Profiler";
 		case MatrixParamEnum : return "MatrixParam";
 		case VectorParamEnum : return "VectorParam";
@@ -467,4 +489,6 @@
 		case OldGradientEnum : return "OldGradient";
 		case OutputFilePointerEnum : return "OutputFilePointer";
+		case OutputFileNameEnum : return "OutputFileName";
+		case LockFileNameEnum : return "LockFileName";
 		case PetscOptionsAnalysesEnum : return "PetscOptionsAnalyses";
 		case PetscOptionsStringsEnum : return "PetscOptionsStrings";
Index: /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp	(revision 13975)
@@ -295,3 +295,2 @@
 	return(iret);
 }
-
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp	(revision 13975)
@@ -27,11 +27,11 @@
 	gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
 	if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
-	
+
 	/*Initialize solution: */
 	solution=new Vector<IssmDouble>(gsize);
-	
+
 	/*Go through elements and plug solution: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->GetSolutionFromInputs(solution);
 	}
Index: /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _GETSOLUTIONFROMINPUTSXX_H */
-
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp	(revision 13975)
@@ -37,8 +37,8 @@
 
 void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
-	
+
 	/*output: */
 	IssmDouble* vector=NULL;
-	
+
 	/*intermediary: */
 	Vector<IssmDouble>* vec_vector=NULL;
Index: /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
-
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp	(revision 13975)
@@ -21,5 +21,5 @@
 		/*Look up in elements*/
 		for(i=0;i<elements->Size();i++){
-			Element* element=(Element*)elements->GetObjectByOffset(i);
+			Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			element->GetVectorFromInputs(vector,name);
 		}
@@ -42,8 +42,8 @@
 
 void GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
-	
+
 	/*output: */
 	IssmDouble* vector=NULL;
-	
+
 	/*intermediary: */
 	Vector<IssmDouble>* vec_vector=NULL;
Index: /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h
===================================================================
--- /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _GETVECTORFROMINPUTSXX_H */
-
Index: /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Gradjx/Gradjx.cpp	(revision 13975)
@@ -19,5 +19,5 @@
 	Vector<IssmDouble>  *gradient      = NULL;
 	Vector<IssmDouble> **gradient_list = NULL;
-	
+
 	/*retrieve some parameters: */
 	parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
Index: /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp
===================================================================
--- /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp	(revision 13975)
@@ -19,7 +19,7 @@
 	Vector<IssmDouble>*      vec_old_floatingice              = NULL;
 	Element* element                          = NULL;
-	
+
 	if(VerboseModule()) _pprintLine_("   Migrating grounding line");
-	
+
 	/*retrieve parameters: */
 	parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
@@ -43,5 +43,5 @@
 	/*Migrate grounding line : */
 	for(i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->MigrateGroundingLine(old_floatingice,vertices_ungrounding);
 	}
@@ -95,5 +95,5 @@
 	/*Fill vector vertices_potentially_floating: */
 	for(i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->PotentialSheetUngrounding(vec_vertices_potentially_ungrounding);
 	}
@@ -121,5 +121,4 @@
 	Element* element                               = NULL;
 
-
 	/*recover parameters: */
 	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
@@ -132,5 +131,5 @@
 	nflipped=1; //bootstrap
 	while(nflipped){
-		
+
 		/*Vector of size number of elements*/
 		vec_elements_neighboring_floatingice=new Vector<IssmDouble>(elements->NumberOfElements(),true);
@@ -138,5 +137,5 @@
 		/*Figure out if any of the nodes of the element will be floating -> elements neighbouting the floating ice*/
 		for(i=0;i<elements->Size();i++){
-			element=(Element*)elements->GetObjectByOffset(i);
+			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(nodes_on_floatingice)?1.0:0.0,INS_VAL);
 		}
@@ -149,5 +148,5 @@
 		local_nflipped=0;
 		for(i=0;i<elements->Size();i++){
-			element=(Element*)elements->GetObjectByOffset(i);
+			element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
 				local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
@@ -155,7 +154,7 @@
 		}
 		vec_nodes_on_floatingice->Assemble();
-		
+
 		#ifdef _HAVE_MPI_
-		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+		MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
 		if(VerboseConvergence()) _pprintLine_("   Additional number of vertices allowed to unground: " << nflipped);
 		#else
Index: /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp
===================================================================
--- /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp	(revision 13975)
@@ -10,14 +10,10 @@
 
 int HoleFillerx(double** pimageout,double* image, int lines,int samps,int smooth){
-	
-	FILE 			*fp1;
-	unsigned long	filesize;
+
 	long			infinit;
 	double          temp;
-	long			i, j, k, l, ii, jj, bytes;
+	long			i, j, k, l, ii, jj;
 	long			iii, jjj;
-	long			test, prevlines, prevpix, test1, test2, thresh,counter;
-	long			bell, cycles, leftovers;
-	float			howlong;
+	long			test;
 	float			nsteps, ssteps, wsteps, esteps;
 	float			nwsteps, nesteps, swsteps, sesteps;
@@ -29,5 +25,5 @@
 	float			ssw, wsw, wnw, nnw;	
 	float			sum;
-	
+
 	time_t			t1, t2;
 
@@ -39,11 +35,8 @@
 	double*         image4=NULL;
 
-	/*Added to original routine: */
-	int             imageoutsize;
-
 	 /*^^^^^^^^^^^^^  Remove pixels close to the holes ^^^^^^^^^^^^^*/
 	image2 = xNew<double>(lines*samps);
 	memcpy(image2,image,lines*samps*sizeof(double));
-	
+
   	for ( i = 0; i < lines; i++ ){
   		for ( j = 0; j < samps; j++ ){
@@ -84,5 +77,5 @@
 
 	again2:	
-	
+
 	#ifdef _DEBUG2_
 		counter=0;
@@ -99,5 +92,5 @@
 		fflush( stdout );
 	#endif
-	
+
 	afterfirst2:
 
@@ -128,5 +121,5 @@
 
 			/* For void edge pixels: */			
-			
+
 			nsteps = 0.0; ssteps = 0.0; esteps = 0.0; wsteps = 0.0;
 			nwsteps = 0.0; nesteps = 0.0; swsteps = 0.0; sesteps = 0.0;
@@ -139,5 +132,4 @@
 			ssw = 0.0; wsw = 0.0; wnw = 0.0; nnw = 0.0;
 
-
 /** NSEW **/
 			for ( ii = i - 1; ii >= 0; ii-- ){   /* North */
@@ -150,10 +142,10 @@
 				if ( *(image2+ii*samps+j) != 0 ){ south = *(image2+ii*samps+j); ssteps = ii - i; break;}
 			}
-				
+
 			for ( jj = j - 1; jj >= 0; jj-- ){   /* West */
 				if ( jj <= 0 ) { west = 0; wsteps = 0; break;}
 				if ( *(image2+i*samps+jj) != 0 ){ west = *(image2+i*samps+jj); wsteps = j - jj; break;}
 			}
-				
+
 			for ( jj = j + 1; jj < samps; jj++ ){ /* East */
 				if ( jj >= samps-1 ){ east = 0; esteps = 0; break;}
@@ -161,5 +153,4 @@
 			}
 
-				
 /** Diagonals  **/						
 			/* Southeast */
@@ -169,5 +160,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ se = *(image2+ii*samps+jj); sesteps = 1.4142 * k; break;}
 			}
-			
+
 			/* Northeast */
 			for ( k = 1; k < infinit; k++ ){
@@ -176,5 +167,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ ne = *(image2+ii*samps+jj); nesteps = 1.4142 * k; break;}
 			}
-			
+
 			/* Northwest */
 			for ( k = 1; k < infinit; k++ ){
@@ -183,5 +174,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ nw = *(image2+ii*samps+jj); nwsteps = 1.4142 * k; break;}
 			}
-			
+
 			/* Southwest */
 			for ( k = 1; k < infinit; k++ ){
@@ -198,5 +189,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ nne = *(image2+ii*samps+jj); nnesteps = 2.2361 * k; break;}
 			}
-			
+
 			/* ENE */
 			for ( k = 1; k < infinit; k++ ){
@@ -205,5 +196,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ ene = *(image2+ii*samps+jj); enesteps = 2.2361 * k; break;}
 			}
-			
+
 			/* ESE */
 			for ( k = 1; k < infinit; k++ ){
@@ -212,5 +203,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ ese = *(image2+ii*samps+jj); esesteps = 2.2361 * k; break;}
 			}
-			
+
 			/* SSE */
 			for ( k = 1; k < infinit; k++ ){
@@ -226,5 +217,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ ssw = *(image2+ii*samps+jj); sswsteps = 2.2361 * k; break;}
 			}
-			
+
 			/* WSW */
 			for ( k = 1; k < infinit; k++ ){
@@ -233,5 +224,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ wsw = *(image2+ii*samps+jj); wswsteps = 2.2361 * k; break;}
 			}
-			
+
 			/* WNW */
 			for ( k = 1; k < infinit; k++ ){
@@ -240,5 +231,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ wnw = *(image2+ii*samps+jj); wnwsteps = 2.2361 * k; break;}
 			}
-			
+
 			/* NNW */
 			for ( k = 1; k < infinit; k++ ){
@@ -247,5 +238,5 @@
 				if ( *(image2+ii*samps+jj) != 0 ){ nnw = *(image2+ii*samps+jj); nnwsteps = 2.2361 * k; break;}
 			}
-			
+
 			elev = 0; range = 0;
 /*NSEW*/			
@@ -259,5 +250,5 @@
 			if ( swsteps > 0.5 ){ elev +=    sw / swsteps; range +=  1.00 / swsteps;}
 			if ( sesteps > 0.5 ){ elev +=    se / sesteps; range +=  1.00 / sesteps;}
-			
+
 /*Other 8*/
 			if ( nnesteps > 0.5 ){ elev += nne / nnesteps; range +=  1.00 / nnesteps;}
@@ -269,5 +260,5 @@
 			if ( wnwsteps > 0.5 ){ elev += wnw / wnwsteps; range +=  1.00 / wnwsteps;}
 			if ( nnwsteps > 0.5 ){ elev += nnw / nnwsteps; range +=  1.00 / nnwsteps;}
-									
+
 			//temp = ( elev / range ) + 0.5 ;
 			temp = ( elev / range );
@@ -275,5 +266,5 @@
 			//if ( temp > 10000 ) temp = 10000;
 			//if ( temp <     0 ) temp =     0;
-			
+
 			#ifdef _DEBUG2_
 				//_printLine_(temp << " " << elev << " " << range << " ");
@@ -284,6 +275,4 @@
 	}
 
-
-
 	for ( i = 0; i < lines; i++ ){
 		for ( j = 0; j < samps; j++ ){
@@ -292,5 +281,4 @@
 	}
 
-
 	for ( i = 0; i < lines; i++ ){
 		for ( j = 0; j < samps; j++ ){
@@ -298,18 +286,15 @@
 		}
 	}
-	
+
 	if ( smooth == 0 ) goto there2;		
-		
-		
+
 /************************ SMOOTH THE RESULT ***********************/		
-		
+
 	image4 = xNew<double>(lines*samps);
 	memcpy(image4,image3,lines*samps*sizeof(double));
-
 
 	for ( i = 0; i < lines; i++ ) {
 		for ( j = 0; j < samps; j++ ) {
 			if ( *(image4+i*samps+j) != 0 ) { *(image3+i*samps+j) = *(image2+i*samps+j) ; continue; }
-
 
 			for ( k = 1; k < infinit; k++ ) { /* Find the smallest box size with data */ 
@@ -324,5 +309,5 @@
 				}
 			}
-		
+
 			k_nowset:
 			k = k / 4; if ( k < 1 ) k = 1; /* Errrrr.  Make it fourth size */
@@ -343,7 +328,5 @@
 	}
 
-		
 there2:		
-
 
 	/*Allocate output image: */
@@ -352,5 +335,5 @@
 
 	time(&t2);	
-	
+
 	#ifdef _DEBUG2_
 		_printString_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
@@ -358,5 +341,5 @@
 		printf ( "\n");
 	#endif
-	
+
 	end:
 
Index: /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.h
===================================================================
--- /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.h	(revision 13975)
@@ -2,5 +2,4 @@
 	HoleFillerx.h
 */
-
 
 #ifndef HOLEFILLERX_H
@@ -12,5 +11,4 @@
 /* local prototypes: */
 int HoleFillerx(double** pimageout,double* imagein, int lines,int samp,int smooth);
-	
+
 #endif /* HOLEFILLERX_H */
-
Index: /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputArtificialNoise(enum_name,min,max);
 	}
Index: /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp	(revision 13975)
@@ -13,5 +13,5 @@
 	/*Go through elemnets, and ask to carry out the operation on inputs: */
 	for(int i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputControlUpdate(scalar,save_parameter);
 	}
Index: /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.cpp	(revision 13975)
@@ -24,5 +24,5 @@
 	/*Go through elements, and ask them to do the job: */
 	for(i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		converged=element->InputConvergence(eps,enums,num_enums,criterionenums,criterionvalues,num_criterionenums);
 		if(!converged) num_notconverged++;
@@ -31,5 +31,5 @@
 	/*In parallel, we need to gather the converged status: */
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( (void*)&num_notconverged,(void*)&total_notconverged,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	MPI_Allreduce ( (void*)&num_notconverged,(void*)&total_notconverged,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
 	num_notconverged=total_notconverged;
 	#endif
Index: /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.h
===================================================================
--- /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.h	(revision 13975)
@@ -11,3 +11,2 @@
 
 #endif  /* _INPUTCONVERGENCEX_H */
-
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp	(revision 13975)
@@ -10,9 +10,9 @@
 
 void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int original_enum, int new_enum){
-	
+
 	/*Go through elemnets, and ask to reinitialie the input: */
 	int      i;
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputDuplicate(original_enum,new_enum);
 	}
Index: /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h
===================================================================
--- /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h	(revision 13975)
@@ -12,3 +12,2 @@
 
 #endif  /* _INPUTDUPLICATEX_H */
-
Index: /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputScalex/InputScalex.cpp	(revision 13975)
@@ -16,5 +16,5 @@
 	/*Go through elemnets, and ask to reinitialie the input: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputScale(enum_type,scale_factor);
 	}
Index: /issm/trunk/src/c/modules/InputScalex/InputScalex.h
===================================================================
--- /issm/trunk/src/c/modules/InputScalex/InputScalex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputScalex/InputScalex.h	(revision 13975)
@@ -12,3 +12,2 @@
 
 #endif  /* _SCALEINPUTX_H */
-
Index: /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp	(revision 13975)
@@ -23,5 +23,5 @@
 	for(int i=0;i<elements->Size();i++){
 
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputToResult(enum_type,step,time);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -23,5 +23,5 @@
 		load->InputUpdateFromConstant(constant,name);
 	}
-	
+
 	for(i=0;i<materials->Size();i++){
 		Material* material=(Material*)materials->GetObjectByOffset(i);
@@ -30,10 +30,10 @@
 }
 void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int    constant, int name){
-	
+
 	int i;
 
 	/*Elements and loads drive the update: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -43,5 +43,5 @@
 		load->InputUpdateFromConstant(constant,name);
 	}
-	
+
 	for(i=0;i<materials->Size();i++){
 		Material* material=(Material*)materials->GetObjectByOffset(i);
@@ -55,5 +55,5 @@
 	/*Elements and loads drive the update: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromConstant(constant,name);
 	}
@@ -63,5 +63,5 @@
 		load->InputUpdateFromConstant(constant,name);
 	}
-	
+
 	for(i=0;i<materials->Size();i++){
 		Material* material=(Material*)materials->GetObjectByOffset(i);
Index: /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h	(revision 13975)
@@ -15,3 +15,2 @@
 
 #endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
-
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp	(revision 13975)
@@ -14,5 +14,5 @@
 	int     i,j,k,l;
 	int     dummy;
-	
+
 	int     numberofvertices;
 	int     nrows;
@@ -35,17 +35,16 @@
 
 	for(i=0;i<numvariables;i++){
-	
+
 		descriptor=variables_descriptors[i];
 
 		/*From descriptor, figure out if the variable is scaled, indexed, nodal, or just a simple variable: */
 		if (strncmp(descriptor,"scaled_",7)==0){
-			
+
 			/*Variable is scaled. Determine root name of variable (ex: scaled_DragCoefficient_1 -> DragCoefficient). Allocate distributed_values and fill the 
 			 * distributed_values with the next npart variables: */
-			
+
 			//strcpy(root,strstr(descriptor,"_")+1); *strstr(root,"_")='\0';
 			memcpy(root,strstr(descriptor,"_")+1,(strlen(strstr(descriptor,"_")+1)+1)*sizeof(char));
 			*strstr(root,"_")='\0';
-
 
 			distributed_values=xNew<double>(npart);
@@ -68,19 +67,18 @@
 
 			#ifdef _DEBUG_
-				PetscSynchronizedPrintf(MPI_COMM_WORLD,"Parameter matrix:");
-				PetscSynchronizedFlush(MPI_COMM_WORLD);
+				PetscSynchronizedPrintf(IssmComm::GetComm(),"Parameter matrix:");
+				PetscSynchronizedFlush(IssmComm::GetComm());
 				for(l=0;l<ncols;l++){
-					PetscSynchronizedPrintf(MPI_COMM_WORLD," time %i\n",l);
-					PetscSynchronizedFlush(MPI_COMM_WORLD);
+					PetscSynchronizedPrintf(IssmComm::GetComm()," time %i\n",l);
+					PetscSynchronizedFlush(IssmComm::GetComm());
 
 					for(k=0;k<numberofvertices;k++){
-						PetscSynchronizedPrintf(MPI_COMM_WORLD," node %i value %g\n",k+1,*(parameter+k*ncols+l));
-						PetscSynchronizedFlush(MPI_COMM_WORLD);
+						PetscSynchronizedPrintf(IssmComm::GetComm()," node %i value %g\n",k+1,*(parameter+k*ncols+l));
+						PetscSynchronizedFlush(IssmComm::GetComm());
 					}
 				}
-				PetscSynchronizedPrintf(MPI_COMM_WORLD," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
-				PetscSynchronizedFlush(MPI_COMM_WORLD);
+				PetscSynchronizedPrintf(IssmComm::GetComm()," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
+				PetscSynchronizedFlush(IssmComm::GetComm());
 			#endif
-			  
 
 			/*Update inputs using the parameter matrix: */
Index: /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h	(revision 13975)
@@ -12,3 +12,2 @@
 
 #endif  /* _INPUTUPDATEFROMDAKOTAXX_H */
-
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 		/*Update elements, nodes, loads and materials from inputs: */
 		for(i=0;i<elements->Size();i++){
-			Element* element=(Element*)elements->GetObjectByOffset(i);
+			Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 			element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
 		}
Index: /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _UPDATEINPUTSFROMMATRIXDAKOTAXX_H */
-
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp	(revision 13975)
@@ -23,5 +23,4 @@
 }
 
-
 void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution){
 
@@ -32,5 +31,5 @@
 	/*Elements drive the update: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromSolution(solution);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h	(revision 13975)
@@ -18,3 +18,2 @@
 
 #endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
-
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp	(revision 13975)
@@ -21,5 +21,4 @@
 }
 
-	
 void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
 
@@ -28,5 +27,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
@@ -46,10 +45,10 @@
 
 void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
-	
+
 	int i;
 
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
@@ -74,5 +73,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVectorDakota(vector,name,type);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h	(revision 13975)
@@ -16,3 +16,2 @@
 
 #endif  /* _UPDATEINPUTSFROMVECTORDAKOTAXX_H */
-
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp	(revision 13975)
@@ -21,5 +21,4 @@
 }
 
-	
 void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector, int name, int type){
 
@@ -28,5 +27,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVector(vector,name,type);
 	}
@@ -46,10 +45,10 @@
 
 void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
-	
+
 	int i;
 
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVector(vector,name,type);
 	}
@@ -74,5 +73,5 @@
 	/*Update elements, nodes, loads and materials from inputs: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->InputUpdateFromVector(vector,name,type);
 	}
Index: /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h
===================================================================
--- /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h	(revision 13975)
@@ -16,3 +16,2 @@
 
 #endif  /* _UPDATEINPUTSFROMVECTORXX_H */
-
Index: /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp	(revision 13975)
@@ -21,9 +21,8 @@
 	/*output: */
 	SeqVec<IssmPDouble>* data_mesh=NULL;
-	
+
 	/*Intermediary*/
 	double* x=NULL;
 	double* y=NULL;
-	double  x_grid,y_grid;
 	int     i;
 
@@ -312,5 +311,5 @@
 	_assert_(x2>x1 && y2>y1);
 	_assert_(x<=x2 && x>=x1 && y<=y2 && y>=y1);
-	
+
 	double xm=(x2-x1)/2;
 	double ym=(y2-y1)/2;
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp	(revision 13975)
@@ -14,15 +14,12 @@
 			double* x_prime, double* y_prime, int nods_prime,
 			double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours){
-	
+
 	/*Output*/
 	SeqVec<IssmPDouble>* data_prime=NULL;
 
 	/*Intermediary*/
-	int    i,j;
+	int    i;
 	int    interpolation_type;
 	bool   debug;
-	double area;
-	double area_1,area_2,area_3;
-	double data_value;
 	double xmin,xmax;
 	double ymin,ymax;
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h	(revision 13975)
@@ -29,5 +29,4 @@
 	double              *incontour;
 
-
 } InterpFromMesh2dxThreadStruct;
 
Index: /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp	(revision 13975)
@@ -18,5 +18,5 @@
 	int                            my_thread   = handle->id;
 	int                            num_threads = handle->num;
-	
+
 	/*recover parameters :*/
 	int     interpolation_type      = gate->interpolation_type;
Index: /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp	(revision 13975)
@@ -69,5 +69,5 @@
 		}
 	}
-	
+
 	/*Get extreme coordinates of the grid*/
 	if (xflip){
Index: /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp
===================================================================
--- /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
 			double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options){
-	
+
 	/*Output*/
 	double* data_interp=NULL;
@@ -25,10 +25,9 @@
 	R2     r;
 	I2     I;
-	int    i,j,k;
+	int    i,j;
 	int    it;
 	int    i0,i1,i2;
 	double areacoord[3];
 	double aa,bb;
-	double data_value;
 	Icoor2 dete[3];
 
Index: /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp	(revision 13975)
@@ -11,20 +11,16 @@
 
 void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type){
-	
 
 	/*intermediary: */
 	int     i,j;
-	bool    transient     = false;
-
-	FILE   *fid           = NULL;
-	int     code          = 0;
-	int     vector_layout = 0;
-	int     counter;
-	int     nods;
-	IssmDouble* times=NULL;
-	IssmDouble* values=NULL;
-	bool    spcpresent=false;
-	int     count=0;
-	int     numberofvertices;
+	bool        transient        = false;
+	FILE       *fid              = NULL;
+	int         code             = 0;
+	int         vector_layout    = 0;
+	IssmDouble *times            = NULL;
+	IssmDouble *values           = NULL;
+	bool        spcpresent       = false;
+	int         count            = 0;
+	int         numberofvertices;
 
 	/*variables being fetched: */
@@ -48,8 +44,8 @@
 		/*static: just create Constraints objects*/
 		count=0;
-	
+
 		/*Create Constraints from x,y,z: */
 		for (i=0;i<numberofvertices;i++){
-			
+
 			/*keep only this partition's nodes:*/
 			if((iomodel->my_vertices[i])){
@@ -78,5 +74,5 @@
 		/*Create constraints from x,y,z: */
 		for (i=0;i<numberofvertices;i++){
-			
+
 			/*keep only this partition's nodes:*/
 			if((iomodel->my_vertices[i])){
Index: /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp	(revision 13975)
@@ -65,3 +65,2 @@
 	return(kfil);
 }
-
Index: /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp
===================================================================
--- /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp	(revision 13975)
@@ -79,5 +79,4 @@
 	kdoc=NULL;
 
-
 /*  write kml file  */
 
@@ -95,3 +94,2 @@
 	return;
 }
-
Index: /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp	(revision 13975)
@@ -25,5 +25,5 @@
 			 int sgn,double cm,double sp){
 
-	int     i,iret=0;
+	int     iret=0;
 	double  *lat=NULL,*lon=NULL;
 
@@ -69,3 +69,2 @@
 	return(iret);
 }
-
Index: /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp	(revision 13975)
@@ -14,6 +14,6 @@
 int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){
 
-	extern int num_procs;
-	extern int my_rank;
+	int num_procs;
+	int my_rank;
 
 	/*output*/
@@ -27,4 +27,8 @@
 	Variogram    *variogram    = NULL;
 	Observations *observations = NULL;
+
+	/*Get my_rank: */
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
 
 	/*Get some Options*/
@@ -64,6 +68,6 @@
 		double *sumpredictions =xNew<double>(n_interp);
 		double *sumerror       =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
-		MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
+		MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(error); error=sumerror;
 		xDelete<double>(predictions); predictions=sumpredictions;
@@ -81,5 +85,5 @@
 #ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(predictions); predictions=sumpredictions;
 #endif
@@ -98,5 +102,5 @@
 #ifdef _HAVE_MPI_
 		double *sumpredictions =xNew<double>(n_interp);
-		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
+		MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
 		xDelete<double>(predictions); predictions=sumpredictions;
 #endif
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp	(revision 13975)
@@ -40,5 +40,5 @@
 		VecMergex(ug,uf,nodes,parameters,FsetEnum);
 	}
-	
+
 	/*Merge s set back into g set: */
 	if(ssize){
Index: /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h
===================================================================
--- /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h	(revision 13975)
@@ -12,3 +12,2 @@
 
 #endif  /* _MERGESOLUTIONFROMFTOGX_H */
-
Index: /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h	(revision 13975)
@@ -8,5 +8,4 @@
 #include "../../include/include.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-
 
 /* local prototypes: */
@@ -89,5 +88,5 @@
 		/*Extrude epart2d to epart, using numlayers: */
 		epart=xNew<int>(numberofelements);
-		
+
 		count=0;
 		for(i=0;i<(numlayers-1);i++){
@@ -100,5 +99,5 @@
 		/*Extrude npart2d to npart, using numlayers: */
 		npart=xNew<int>(numberofnodes);
-		
+
 		count=0;
 		for(i=0;i<(numlayers);i++){
@@ -109,5 +108,5 @@
 		}
 	}
-	
+
 	/*Assign output pointer:*/
 	*pepart=epart;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp	(revision 13975)
@@ -3,5 +3,5 @@
 
 #include "./MeshProfileIntersectionx.h"
-		
+
 void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment){
 
@@ -9,10 +9,8 @@
 	 * If they do, create a Segment object with the intersection, and add to segments_dataset dataset: */
 
-	int i;
-	double alpha;
 	double alpha1,alpha2;
 	double beta1,beta2;
 	double gamma1,gamma2;
-	
+
 	int    edge1,edge2,edge3;
 
@@ -21,5 +19,4 @@
 	double xfinal[2],yfinal[2];
 
-	
 	/*edge 1: */
 	xel[0]=xnodes[0];  yel[0]=ynodes[0]; xel[1]=xnodes[1];  yel[1]=ynodes[1];
@@ -41,5 +38,5 @@
 	}
 	else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
-	
+
 		/*segment interscts 2 opposite edges of our triangle, at 2 segment coordinates, pick up the lowest (coord1) and highest (coord2): */
 		if((edge1==IntersectEnum) && (edge2==IntersectEnum)) {coord1=min(alpha1,beta1); coord2=max(alpha1,beta1);}
@@ -77,5 +74,5 @@
 			coord2=1.0;
 		}
-		
+
 		xfinal[0]=xsegment[0]+coord1*(xsegment[1]-xsegment[0]);
 		xfinal[1]=xsegment[0]+coord2*(xsegment[1]-xsegment[0]);
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp	(revision 13975)
@@ -3,5 +3,5 @@
 
 #include "./MeshProfileIntersectionx.h"
-		
+
 void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes){
 
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp	(revision 13975)
@@ -7,5 +7,4 @@
 
 	int i,j,k;
-	int m,n;
 
 	/*Contour:*/
@@ -32,5 +31,5 @@
 	/*Loop through all contours: */
 	for (i=0;i<numcontours;i++){
-		
+
 		/*retrieve contour info: */
 		contouri=*(contours+i);
@@ -41,5 +40,5 @@
 		/*determine segmentsi and numsegsi for this contour and the mesh intersection: */
 		MeshSegmentsIntersection(&segmentsi,&numsegsi,index,x,y,nel,nods,xc,yc,numnodes);
-		
+
 		/*save segmentsi: */
 		allsegments[i]=segmentsi;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h	(revision 13975)
@@ -2,5 +2,4 @@
 	MeshProfileIntersectionx.h
 */
-
 
 #ifndef _MESHPROFILEINTERSECTIONX_H
@@ -19,3 +18,2 @@
 
 #endif /* _MESHPROFILEINTERSECTIONX_H */
-
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 	Segment<double>* segment=NULL;
 	int     numsegs;
-	
+
 	/*intermediary: */
 	DataSet* segments_dataset=NULL;
@@ -35,5 +35,5 @@
 	for(i=0;i<numsegs;i++){
 		Segment<double>* segment=(Segment<double>*)segments_dataset->GetObjectByOffset(i);
-		
+
 		/*x1,y1,x2,y2 then element_id: */
 		*(segments+5*i+0)=segment->x1;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp	(revision 13975)
@@ -19,8 +19,7 @@
 	y3=ynodes[2];
 
-
 	/*compute determinant: */
 	det=x1*y2-x1*y3-x3*y2-x2*y1+x2*y3+x3*y1;
-	
+
 	/*area coordinates: */
 	lambda1=((y2-y3)*(x-x3)+(x3-x2)*(y-y3))/det;
Index: /issm/trunk/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp
===================================================================
--- /issm/trunk/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 	double alpha=-1;
 	double beta=-1;
-	
+
 	double xA,xB,xC,xD,yA,yB,yC,yD;
 	double O2A[2],O2B[2],O1C[2],O1D[2];
@@ -29,5 +29,4 @@
 	O1C[0]=xC -(xA/2+xB/2); O1C[1]=yC -(yA/2+yB/2);
 	O1D[0]=xD -(xA/2+xB/2); O1D[1]=yD -(yA/2+yB/2);
-
 
 	n1[0]=yA-yB; n1[1]=xB-xA;  //normal vector to segA
Index: /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp	(revision 13975)
@@ -7,21 +7,29 @@
 #include "../../../io/io.h"
 #include "../../../EnumDefinitions/EnumDefinitions.h"
-#include "../../../classes/objects/objects.h"
+#include "../../../classes/classes.h"
 #include "../../../shared/shared.h"
 #include "../../../include/include.h"
+#include "../../Solverx/Solverx.h"
 #include "../ModelProcessorx.h"
 
 void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
-	
-	int         i,j;
+
+	int         i;
 	Parameters *parameters       = NULL;
 	bool        autodiff_analysis;
-	int*        dependents       = NULL;
-	int         num_dependents;
-	int*        independents       = NULL;
-	int         num_independents;
-	int         numberofvertices;
+	int         num_dependent_objects;
+	int         num_dep=0;
+	int*        names=NULL;
+	int*        types=NULL;
+	int         dummy;
+	char*       autodiff_driver=NULL;
+	int*        indices=NULL;
+	int         num_indices;
+
 	IssmDouble* xp=NULL;
-	
+	IssmDouble* xp_backup=NULL;
+	int         num_ind,local_num_ind;
+	DataSet*    dependent_objects=NULL;
+
 	/*Get parameters: */
 	parameters=*pparameters;
@@ -29,37 +37,99 @@
 	/*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);
+		#ifdef _HAVE_ADOLC_
 
-		/*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));
+		/*Copy some parameters from IoModel to parameters dataset: */
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffKeepEnum));
+
+		/*retrieve driver: {{{*/
+		iomodel->Constant(&autodiff_driver,AutodiffDriverEnum);
+		parameters->AddObject(iomodel->CopyConstantObject(AutodiffDriverEnum));
+
+		if(strcmp(autodiff_driver,"fos_forward")==0){
+			parameters->AddObject(iomodel->CopyConstantObject(AutodiffFosForwardIndexEnum));
 		}
+		else if(strcmp(autodiff_driver,"fos_reverse")==0){
+			parameters->AddObject(iomodel->CopyConstantObject(AutodiffFosReverseIndexEnum));
+		}
+		else if(strcmp(autodiff_driver,"fov_forward")==0){
+			/*Retrieve list of indices: */
+			iomodel->FetchData(&indices,&num_indices,&dummy,AutodiffFovForwardIndicesEnum);
+			parameters->AddObject(new IntMatParam(AutodiffFovForwardIndicesEnum,indices,num_indices,1));
+			xDelete<int>(indices);
+		}
+		/*}}}*/
+		/*Deal with dependents first: {{{*/
+		iomodel->Constant(&num_dependent_objects,AutodiffNumDependentObjectsEnum);
+		dependent_objects=new DataSet();
+		num_dep=0;
 
-		/*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));
+		if(num_dependent_objects){
+			iomodel->FetchData(&names,&dummy,&dummy,AutodiffDependentObjectNamesEnum);
+			iomodel->FetchData(&types,&dummy,&dummy,AutodiffDependentObjectTypesEnum);
+			iomodel->FetchData(&indices,&dummy,&dummy,AutodiffDependentObjectIndicesEnum);
 
-			/*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];
-				}
+			for(i=0;i<num_dependent_objects;i++){
+				DependentObject* dep=new DependentObject(names[i],types[i],indices[i]);
+				dependent_objects->AddObject(dep);
+				num_dep+=dep->NumDependents();
 			}
-			parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_independents*numberofvertices));
+
+			/*Free ressources:*/
+			xDelete<int>(names);
+			xDelete<int>(types);
 		}
+		parameters->AddObject(new DataSetParam(AutodiffDependentObjectsEnum,dependent_objects));
+		parameters->AddObject(new IntParam(AutodiffNumDependentsEnum,num_dep));
 
-		/*Assign output pointer: */
-		*pparameters=parameters;
+		delete dependent_objects;
+		/*}}}*/
+		/*Deal with independents: {{{*/
+
+		/*Independents have already been recovered in iomodel->DeclareIndependents. Just do some more processing. 
+		 *In particular, figure out num_independents, and create the state vector xp, or size num_independents x 1 :*/
+		num_ind=0;
+		for(i=0;i<iomodel->independent_objects->Size();i++){
+			IndependentObject* ind=(IndependentObject*)iomodel->independent_objects->GetObjectByOffset(i);
+			num_ind+=ind->NumIndependents();
+		}
+		if(num_ind){
+			xp=xNew<IssmDouble>(num_ind);
+			xp_backup=xp;
+			for(i=0;i<iomodel->independent_objects->Size();i++){
+				IndependentObject* ind=(IndependentObject*)iomodel->independent_objects->GetObjectByOffset(i);
+				ind->FillIndependents(iomodel->data,xp);
+				local_num_ind=ind->NumIndependents(); xp=xp+local_num_ind;
+			}
+			xp=xp_backup; parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_ind));
+		}
+		parameters->AddObject(new IntParam(AutodiffNumIndependentsEnum,num_ind));
+
+		/*Don't forget to copy  iomodel->independent_objects to parameters: */
+		parameters->AddObject(new DataSetParam(AutodiffIndependentObjectsEnum,iomodel->independent_objects));
+		/*}}}*/
+
+		#endif
 	}
+
+	#ifdef _HAVE_ADOLC_
+		/*initialize a placeholder to store solver pointers: {{{*/
+		GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
+		// to save some space:
+		// we know we won't use adolc inside of  the solver:
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->nestedAdolc=false;
+		// the solution vector is just allocated and doesn't have a meaningfull prior value
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_y_priorRequired=false;
+		// the solver wrapper makes sure the matrix and the right hand side don't change
+		theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_x_changes=false;
+		parameters->AddObject(theAdolcEDF_p);
+		/*}}}*/
+	#endif
+
+	/*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 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp	(revision 13975)
@@ -10,14 +10,10 @@
 void	CreateConstraintsBalancethickness(Constraints** pconstraints, IoModel* iomodel){
 
+	/*Fetch parameters: */
 	int    stabilization;	
-	
-	/*Fetch parameters: */
 	iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
 
-	/*Output*/
-	Constraints* constraints = NULL;
-
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp	(revision 13975)
@@ -14,5 +14,4 @@
 
 	/*Intermediary*/
-	int i;
 	int element;
 	int stabilization;
@@ -23,13 +22,10 @@
 	iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
 
-	/*Output*/
-	Loads*    loads    = NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
 	if(!loads) loads = new Loads();
-	
+
 	/*Loads only in DG*/
 	if (stabilization==3){
@@ -39,5 +35,5 @@
 
 		/*First load data:*/
-		for (i=0;i<numberofedges;i++){
+		for (int i=0;i<numberofedges;i++){
 
 			/*Get left and right elements*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp	(revision 13975)
@@ -26,7 +26,4 @@
 	int    stabilization;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -36,5 +33,5 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp	(revision 13975)
@@ -13,9 +13,6 @@
 void	CreateConstraintsBedSlope(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Output*/
-	Constraints* constraints = NULL;
-	
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp	(revision 13975)
@@ -13,9 +13,6 @@
 void	CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel){
 
-	/*DataSet*/
-	Loads*    loads    = NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp	(revision 13975)
@@ -18,21 +18,18 @@
 	int i;
 	bool continuous_galerkin=true;
-	int    numberofvertices;
-
-	/*DataSets: */
-	Nodes*    nodes = NULL;
 
 	/*Fetch parameters: */
+	int    numberofvertices;
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
 	if(!nodes) nodes = new Nodes();
-	
+
 	/*Continuous Galerkin partition of nodes: */
 	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-	
+
 	/*First fetch data: */
 	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
@@ -40,5 +37,5 @@
 	for (i=0;i<numberofvertices;i++){
 		if(iomodel->my_vertices[i]){
-			
+
 			/*Add node to nodes dataset: */
 			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BedSlopeAnalysisEnum));
@@ -49,5 +46,5 @@
 	/*Clean fetched data: */
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp	(revision 13975)
@@ -42,5 +42,5 @@
 		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
 	}
-	
+
 	/*Free data: */
 	iomodel->DeleteData(1,MeshElementsEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp	(revision 13975)
@@ -13,6 +13,5 @@
 
 void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
-	
-	int         i;
+
 	Parameters *parameters       = NULL;
 	bool        control_analysis;
@@ -21,8 +20,8 @@
 	int         num_cm_responses;
 	int        *control_type     = NULL;
-	IssmDouble     *cm_responses     = NULL;
-	IssmDouble     *cm_jump          = NULL;
-	IssmDouble     *optscal          = NULL;
-	IssmDouble     *maxiter          = NULL;
+	IssmDouble *cm_responses     = NULL;
+	IssmDouble *cm_jump          = NULL;
+	IssmDouble *optscal          = NULL;
+	IssmDouble *maxiter          = NULL;
 
 	/*Get parameters: */
Index: /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp	(revision 13975)
@@ -25,5 +25,4 @@
 	bool   control_analysis;
 
-	
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
@@ -65,5 +64,5 @@
 		}
 	}
-	
+
 	/*Free data: */
 	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 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp	(revision 13975)
@@ -15,5 +15,4 @@
 #include "./ModelProcessorx.h"
 
-
 void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
 
@@ -22,5 +21,5 @@
 	Materials  *materials  = NULL;
 	Parameters *parameters = NULL;
-			
+
 	/*Create elements, vertices and materials, independent of analysis_type: */
 	CreateElementsVerticesAndMaterials(pelements, pvertices, pmaterials, iomodel,nummodels);
@@ -40,5 +39,5 @@
 			UpdateElementsDiagnosticHoriz(elements,iomodel,analysis_counter,analysis_type);
 			break;
-		
+
 		case DiagnosticVertAnalysisEnum:
 			CreateNodesDiagnosticVert(pnodes, iomodel);
@@ -47,5 +46,5 @@
 			UpdateElementsDiagnosticVert(elements,iomodel,analysis_counter,analysis_type);
 			break;
-	
+
 		case DiagnosticHutterAnalysisEnum:
 			CreateNodesDiagnosticHutter(pnodes, iomodel);
@@ -55,5 +54,5 @@
 			break;
 		#endif
-		
+
 		#ifdef _HAVE_HYDROLOGY_
 		case HydrologyAnalysisEnum:
@@ -72,5 +71,5 @@
 			UpdateElementsThermal(elements,iomodel,analysis_counter,analysis_type);
 			break;
-	
+
 		case EnthalpyAnalysisEnum:
 			CreateNodesEnthalpy(pnodes, iomodel);
@@ -79,5 +78,5 @@
 			UpdateElementsEnthalpy(elements,iomodel,analysis_counter,analysis_type);
 			break;
-		
+
 		case MeltingAnalysisEnum:
 			CreateNodesMelting(pnodes, iomodel);
@@ -122,5 +121,4 @@
 		#endif
 
-
 		default:
 			_error_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp	(revision 13975)
@@ -16,5 +16,5 @@
 
 	/*Intermediary*/
-	int i,j,k,n;
+	int i;
 	int dim,materials_type;
 	int numberofelements;
@@ -41,8 +41,8 @@
 	vertices  = new Vertices();
 	materials = new Materials();
-	
+
 	/*First, partition elements and vertices. Nodes will partitioned on a per analysis_type basis. If partitining already done, ignore: */
 	ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
-	
+
 	iomodel->FetchData(2,MeshElementsEnum,MeshElementconnectivityEnum);
 	#ifdef _HAVE_3D_
@@ -50,5 +50,5 @@
 	#endif
 	if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
-	
+
 	/*Create elements*/
 	for (i=0;i<numberofelements;i++){
@@ -62,5 +62,5 @@
 		}
 	}
-	
+
 	/*Create materials*/
 	switch(materials_type){
@@ -84,5 +84,5 @@
 	/*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
-	
+
 	/*Create vertices: */
 
@@ -90,10 +90,10 @@
 	iomodel->FetchData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
 	CreateNumberNodeToElementConnectivity(iomodel);
-	
+
 	for (i=0;i<numberofvertices;i++){
 
 		/*vertices and nodes (same number, as we are running continuous galerkin formulation): */
 		if(iomodel->my_vertices[i]){
-			
+
 			/*Add vertex to vertices dataset: */
 			vertices->AddObject(new Vertex(i+1,i,i,iomodel));
Index: /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp	(revision 13975)
@@ -8,5 +8,4 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-
 
 #include "../../Container/Container.h"
@@ -20,6 +19,6 @@
 
 void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter){
-	
-	int         i;
+
+	int         i,j,m,k;
 	int         numoutputs;
 	Parameters *parameters       = NULL;
@@ -27,9 +26,23 @@
 	bool        isdelta18o;
 
+	/*parameters for mass flux: {{{*/
+	int      mass_flux_num_profiles=0;
+	bool     qmu_mass_flux_present=false;
+	bool     autodiff_mass_flux_present=false;
+	bool     mass_flux_present=false;
+	IssmDouble** array=NULL;
+	int*     mdims_array=NULL;
+	int*     ndims_array=NULL;
+	IssmDouble*  temp_matrix=NULL;
+	int      temp_m,temp_n;
+	IssmDouble*  matrix=NULL;
+	int      count;
+	/*}}}*/
+
 	if(*pparameters)return; //do not create parameters twice!
 
 	/*Initialize dataset: */
 	parameters = new Parameters();
-		
+
 	/*Copy some constants from iomodel */
 	parameters->AddObject(iomodel->CopyConstantObject(MeshDimensionEnum));
@@ -127,13 +140,81 @@
 	if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
 	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));
 	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));
 	iomodel->DeleteData(requestedoutputs,SteadystateRequestedOutputsEnum);
-	
+
+	iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,PrognosticRequestedOutputsEnum);
+	parameters->AddObject(new IntParam(PrognosticNumRequestedOutputsEnum,numoutputs));
+	if(numoutputs)parameters->AddObject(new IntVecParam(PrognosticRequestedOutputsEnum,requestedoutputs,numoutputs));
+	iomodel->DeleteData(requestedoutputs,PrognosticRequestedOutputsEnum);
+
+	/*Deal with mass flux segments: {{{*/
+	iomodel->FetchData(&qmu_mass_flux_present,QmuMassFluxSegmentsPresentEnum);
+	iomodel->FetchData(&autodiff_mass_flux_present,AutodiffMassFluxSegmentsPresentEnum);
+
+	if(qmu_mass_flux_present || autodiff_mass_flux_present)mass_flux_present=true;
+	else mass_flux_present=false;
+	parameters->AddObject(new BoolParam(MassFluxSegmentsPresentEnum,mass_flux_present));
+
+	if(mass_flux_present){
+
+		/*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,&mass_flux_num_profiles,MassFluxSegmentsEnum);
+		if(mass_flux_num_profiles==0)_error_("mass_flux_num_profiles is 0, when MassFlux computations were requested!");
+
+		/*Go through segments, and extract those that belong to this cpu: */
+		for(i=0;i<mass_flux_num_profiles;i++){
+			temp_matrix=array[i];
+			temp_m=mdims_array[i];
+			temp_n=ndims_array[i];
+
+			m=0;
+			for(j=0;j<temp_m;j++){
+				if (  iomodel->my_elements[reCast<int>(*(temp_matrix+5*j+4))-1] )m++;
+			}
+			if(m){
+				matrix=xNewZeroInit<IssmDouble>(5*m);
+				count=0;
+				for(j=0;j<temp_m;j++){
+					if (iomodel->my_elements[reCast<int>(*(temp_matrix+5*j+4))-1]){
+						for(k=0;k<5;k++)*(matrix+5*count+k)=*(temp_matrix+5*j+k);
+						count++;
+					}
+				}
+			}
+			else{
+				matrix=NULL;
+			}
+
+			/*Assign: */
+			array[i]=matrix;
+			mdims_array[i]=m;
+			ndims_array[i]=5;
+
+			/*Free temporary matrix: */
+			xDelete<IssmDouble>(temp_matrix);
+		}
+
+		/*Ok, we have an array of segments, different on every cpu. Create a DoubleMatArrayParam object with it: */
+		parameters->AddObject(new DoubleMatArrayParam(MassFluxSegmentsEnum,array,mass_flux_num_profiles,mdims_array,ndims_array));
+
+		/*Free data: */
+		for(i=0;i<mass_flux_num_profiles;i++){
+			IssmDouble* matrix=array[i];
+			xDelete<IssmDouble>(matrix);
+		}
+		xDelete<int>(mdims_array); 
+		xDelete<int>(ndims_array);
+		xDelete<IssmDouble*>(array);
+	}
+	/*}}}*/
+
 	/*Before returning, create parameters in case we are running Qmu or control types runs: */
 	#ifdef _HAVE_CONTROL_
Index: /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp	(revision 13975)
@@ -16,9 +16,7 @@
 
 	/*variable declarations: {{{*/
-	int i,j,k;
-	
+	int i;
 	Parameters* parameters = NULL;
-	int      second_count;
-	
+
 	int*     part=NULL;
 	double*  dpart=NULL;
@@ -35,21 +33,8 @@
 	char* qmuerrname=NULL;
 	char* qmuoutname=NULL;
-	
+
 	//descriptors:
 	char tag[50];
-	
-	/*parameters for mass flux: */
-	bool     qmu_mass_flux_present=false;
-	int qmu_mass_flux_num_profiles=0;
-	double** array=NULL;
-	int*     mdims_array=NULL;
-	int*     ndims_array=NULL;
-	
-	double*  matrix=NULL;
-	double*  temp_matrix=NULL;
-	int      M;
-	int      temp_m,temp_n;
-	int      m,n;
-	int      count;
+
 	bool     dakota_analysis=false;
 	char*    name=NULL;
@@ -60,5 +45,5 @@
 
 	/*}}}*/
-	
+
 	/*recover parameters : */
 	parameters=*pparameters;
@@ -102,5 +87,5 @@
 		/*Deal with partitioning: {{{*/
 		/*partition vertices in iomodel->qmu_npart parts, unless a partition is already present: */
-		
+
 		parameters->AddObject(iomodel->CopyConstantObject(QmuNumberofpartitionsEnum));
 		iomodel->FetchData(&dpart,NULL,NULL,QmuPartitionEnum);
@@ -117,5 +102,5 @@
 		/*}}}*/
 		/*Deal with data needed because of qmu variables: {{{*/
-		
+
 		for(i=0;i<numvariabledescriptors;i++){
 
@@ -123,5 +108,5 @@
 				/*Ok, we are dealing with a variable that is distributed over nodes. Recover the name of the variable (ex: scaled_Thickness): */
 				sscanf(variabledescriptors[i],"scaled_%s",tag);
-				
+
 				/*Recover data: */
 				iomodel->FetchData(&dakota_parameter,&nrows,&ncols,StringToEnumx(tag));
@@ -134,69 +119,8 @@
 					parameters->AddObject(new DoubleTransientMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
 				}
-				
+
 				/*Free ressources:*/
 				xDelete<double>(dakota_parameter);
 			}
-		}
-		/*}}}*/
-		/*Deal with data needed to compute qmu responses: {{{*/
-		for(i=0;i<numresponsedescriptors;i++){
-			
-			if(strncmp(responsedescriptors[i],"indexed_MassFlux",16)==0){
-				qmu_mass_flux_present=true;
-			}
-		}
-		
-		
-		if(qmu_mass_flux_present){
-			
-			/*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */ 
-			iomodel->FetchData(&array,&mdims_array,&ndims_array,&qmu_mass_flux_num_profiles,QmuMassFluxSegmentsEnum);
-			if(qmu_mass_flux_num_profiles==0)_error_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
-
-			/*Go through segments, and extract those that belong to this cpu: */
-			for(i=0;i<qmu_mass_flux_num_profiles;i++){
-				temp_matrix=array[i];
-				temp_m=mdims_array[i];
-				temp_n=ndims_array[i];
-
-				m=0;
-				for(j=0;j<temp_m;j++){
-					if (  iomodel->my_elements[(int)(*(temp_matrix+5*j+4))-1])m++;
-				}
-				if(m){
-					matrix=xNewZeroInit<double>(5*m);
-					count=0;
-					for(j=0;j<temp_m;j++){
-						if (iomodel->my_elements[(int)*(temp_matrix+5*j+4)-1]){
-							for(k=0;k<5;k++)*(matrix+5*count+k)=*(temp_matrix+5*j+k);
-							count++;
-						}
-					}
-				}
-				else{
-					matrix=NULL;
-				}
-
-				/*Assign: */
-				array[i]=matrix;
-				mdims_array[i]=m;
-				ndims_array[i]=5;
-
-				/*Free temporary matrix: */
-				xDelete<double>(temp_matrix);
-			}
-
-			/*Ok, we have an array of segments, different on every cpu. Create a DoubleMatArrayParam object with it: */
-			parameters->AddObject(new DoubleMatArrayParam(QmuMassFluxSegmentsEnum,array,qmu_mass_flux_num_profiles,mdims_array,ndims_array));
-
-			/*Free data: */
-			for(i=0;i<qmu_mass_flux_num_profiles;i++){
-				double* matrix=array[i];
-				xDelete<double>(matrix);
-			}
-			xDelete<int>(mdims_array); 
-			xDelete<int>(ndims_array);
-			xDelete<double*>(array);
 		}
 		/*}}}*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp	(revision 13975)
@@ -44,5 +44,4 @@
 	Constraints *constraints      = NULL;
 	SpcStatic   *spcstatic        = NULL;
-	int          node1,node2;
 	int          dim;
 	int          numberofvertices;
@@ -64,5 +63,5 @@
 	/*Create constraints if they do not exist yet*/
 	if(!constraints) constraints = new Constraints();
-	
+
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
 	if(!ismacayealpattyn & !isstokes & !isl1l2){
@@ -70,5 +69,5 @@
 		return;
 	}
-	
+
 	/*Constraints: fetch data: */
 	iomodel->FetchData(&spcvx,&Mx,&Nx,DiagnosticSpcvxEnum);
@@ -324,5 +323,5 @@
 		}
 	}
-	  
+
 	/*Free data: */
 	iomodel->DeleteData(spcvx,DiagnosticSpcvxEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp	(revision 13975)
@@ -14,7 +14,5 @@
 
 	/*DataSets*/
-	Loads     *loads     = NULL;
 	Icefront  *icefront  = NULL;
-	Riftfront *riftfront = NULL;
 	Pengrid   *pengrid   = NULL;
 
@@ -48,5 +46,5 @@
 
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
@@ -58,5 +56,5 @@
 		return;
 	}
-	
+
 	/*Create pressure loads as boundary conditions. Pay attention to the partitioning if we are running in parallel (the nodes
 	 * referenced by a certain load must belong to the cluster node): */
@@ -70,5 +68,5 @@
 	/*First load data:*/
 	for (i=0;i<numberofpressureloads;i++){
-		
+
 		/*Retrieve element to which this icefront belongs: */
 		if (dim==2) segment_width=4; 
@@ -78,5 +76,5 @@
 		/*Now, if this element is not in the partition, pass: */
 		if(!iomodel->my_elements[element]) continue;
-		
+
 		/*Do not create ice front if Hutter or Stokes elements*/
 		if (reCast<int,IssmDouble>(*(elements_type+element))==HutterApproximationEnum) continue;
@@ -132,8 +130,7 @@
 	iomodel->DeleteData(pressureload,DiagnosticIcefrontEnum);
 
-
 	/*Create Penpair for penalties: */
 	iomodel->FetchData(&penalties,&numpenalties,NULL,DiagnosticVertexPairingEnum);
-	
+
 	for(i=0;i<numpenalties;i++){
 
@@ -167,5 +164,5 @@
 		}
 		iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
-		xDelete<Riftfront>(riftfront);
+		xDelete<IssmDouble>(riftinfo);
 	}
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp	(revision 13975)
@@ -21,7 +21,4 @@
 	bool   isstokes,isl1l2,ismacayealpattyn;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
@@ -31,9 +28,9 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*First create nodes*/
 	if(!nodes) nodes = new Nodes();
-	
+
 	/*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
 	if(!ismacayealpattyn & !isstokes & !isl1l2){
@@ -48,9 +45,9 @@
 	iomodel->FetchData(9,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBordermacayealEnum,FlowequationBorderstokesEnum,
 				MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MaskVertexonwaterEnum,FlowequationVertexEquationEnum,DiagnosticReferentialEnum);
-	
+
 	for (i=0;i<numberofvertices;i++){
 
 		if(iomodel->my_vertices[i]){
-			
+
 			/*Add node to nodes dataset: */
 			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,DiagnosticHorizAnalysisEnum));
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp	(revision 13975)
@@ -85,9 +85,9 @@
 	elements->InputDuplicate(VxEnum,InversionVxObsEnum);
 	if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
-	
+
 	elements->InputDuplicate(VyEnum,VyPicardEnum);
 	elements->InputDuplicate(VyEnum,InversionVyObsEnum);
 	if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
-	
+
 	if(dim==3){
 		elements->InputDuplicate(VzEnum,VzPicardEnum);
@@ -95,5 +95,5 @@
 		if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
 	}
-	
+
 	/*Free data: */
 	iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp	(revision 13975)
@@ -75,5 +75,5 @@
 	/*Free data: */
 	iomodel->DeleteData(3,DiagnosticSpcvxEnum,DiagnosticSpcvyEnum,FlowequationVertexEquationEnum);
-	
+
 	/*Assign output pointer: */
 	*pconstraints=constraints;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp	(revision 13975)
@@ -13,13 +13,10 @@
 void	CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel){
 
-	/*DataSet*/
-	Loads* loads=NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
 	if(!loads) loads = new Loads();
-	
+
 	/*Assign output pointer: */
 	*ploads=loads;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp	(revision 13975)
@@ -21,7 +21,4 @@
 	bool   ishutter;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
@@ -29,5 +26,5 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp	(revision 13975)
@@ -19,5 +19,4 @@
 	bool   ishutter;
 
-	
 	/*Fetch data needed: */
 	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
@@ -38,8 +37,8 @@
 		}
 	}
-	
+
 	iomodel->FetchDataToInput(elements,ThicknessEnum);
 	iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum);
-	
+
 	/*Free data: */
 	iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp	(revision 13975)
@@ -20,7 +20,4 @@
 	int    numberofvertices;
 
-	/*Output*/
-	Constraints* constraints = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -29,5 +26,5 @@
 
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp	(revision 13975)
@@ -13,9 +13,6 @@
 void	CreateLoadsDiagnosticVert(Loads** ploads, IoModel* iomodel){
 
-	/*DataSet*/
-	Loads* loads=NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp	(revision 13975)
@@ -21,7 +21,4 @@
 	int    numberofvertices;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -29,5 +26,5 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
@@ -42,5 +39,5 @@
 	/*Continuous Galerkin partition of nodes: */
 	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-	
+
 	/*First fetch data: */
 	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
@@ -57,5 +54,5 @@
 	/*Clean fetched data: */
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp	(revision 13975)
@@ -54,4 +54,4 @@
 	/*Free data: */
 	iomodel->DeleteData(1,MeshElementsEnum);
-	
+
 }
Index: /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp	(revision 13975)
@@ -6,5 +6,5 @@
 #include "../../include/include.h"
 #include "../../EnumDefinitions/EnumDefinitions.h"
-	
+
 void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type){
 
@@ -13,5 +13,4 @@
 
 	int numdofs=2; //default numdofs
-	int i;
 	int* doftype=NULL;
 
Index: /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp	(revision 13975)
@@ -22,6 +22,6 @@
 	int i;
 
-	extern int my_rank;
-	extern int num_procs;
+	int my_rank;
+	int num_procs;
 	int    numberofelements;
 	int    numberofvertices;
@@ -46,4 +46,8 @@
 	IssmDouble* riftinfo=NULL;
 	IssmDouble* vertex_pairing=NULL;
+
+	/*Get my_rank:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
 
 	/*Fetch parameters: */
@@ -102,5 +106,5 @@
 
 			my_elements[i]=true;
-			
+
 			/*Now that we are here, we can also start building the list of vertices belonging to this cpu partition: we use 
 			 *the  element index to do this. For each element n, we know index[n][0:2] holds the indices (matlab indexing) 
@@ -110,5 +114,5 @@
 			my_vertices[reCast<int>(*(elements+elements_width*i+1))-1]=1;
 			my_vertices[reCast<int>(*(elements+elements_width*i+2))-1]=1;
-			
+
 			if(elements_width==6){
 				my_vertices[reCast<int>(*(elements+elements_width*i+3))-1]=1;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp	(revision 13975)
@@ -23,10 +23,9 @@
 	IssmDouble heatcapacity;
 	IssmDouble referencetemperature;
-	
+
 	/*Output*/
 	IssmDouble *spcvector  = NULL;
 	IssmDouble* times=NULL;
 	IssmDouble* values=NULL;
-	Constraints* constraints = NULL;
 
 	/*Fetch parameters: */
@@ -37,5 +36,5 @@
 
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
@@ -85,5 +84,5 @@
 		/*Create constraints from x,y,z: */
 		for (i=0;i<numberofvertices;i++){
-			
+
 			/*keep only this partition's nodes:*/
 			if((iomodel->my_vertices[i])){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp	(revision 13975)
@@ -13,14 +13,10 @@
 void	CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel){
 
-	/*DataSet*/
-	Loads* loads=NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
 	if(!loads) loads = new Loads();
 
-
 	/*Assign output pointer: */
 	*ploads=loads;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp	(revision 13975)
@@ -20,12 +20,9 @@
 	int    numberofvertices;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	
+
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
@@ -40,5 +37,5 @@
 	for (i=0;i<numberofvertices;i++){
 		if(iomodel->my_vertices[i]){
-			
+
 			/*Add node to nodes dataset: */
 			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,EnthalpyAnalysisEnum));
@@ -49,5 +46,5 @@
 	/*Clean fetched data: */
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp	(revision 13975)
@@ -59,5 +59,5 @@
 	iomodel->FetchDataToInput(elements,VyEnum);
 	iomodel->FetchDataToInput(elements,VzEnum);
-	
+
 	/*Free data: */
 	iomodel->DeleteData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp	(revision 13975)
@@ -14,14 +14,11 @@
 void	CreateConstraintsHydrology(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Output*/
-	Constraints *constraints = NULL;
-
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
 	if(!constraints) constraints = new Constraints();
 	IoModelToConstraintsx(constraints,iomodel,HydrologySpcwatercolumnEnum,HydrologyAnalysisEnum);
-	
+
 	/*Assign output pointer: */
 	*pconstraints=constraints;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp	(revision 13975)
@@ -13,12 +13,6 @@
 void	CreateLoadsHydrology(Loads** ploads, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-
-	/*DataSet*/
-	Loads*    loads    = NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp	(revision 13975)
@@ -20,12 +20,9 @@
 	int    numberofvertices;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
-	
+
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
@@ -46,5 +43,5 @@
 	}
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp	(revision 13975)
@@ -17,5 +17,5 @@
 
 	int    numberofelements;
-	
+
 	/*Fetch data needed: */
 	iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp	(revision 13975)
@@ -13,13 +13,6 @@
 void	CreateConstraintsMelting(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-	int count;
-	
-	/*Intermediary*/
-	Constraints* constraints = NULL;
-
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp	(revision 13975)
@@ -14,12 +14,6 @@
 
 	/*Intermediary*/
-	int i;
-	int    dim;
-	int    numberofvertices;
-
-	/*DataSet*/
-	Loads*    loads    = NULL;
-
-	/*Fetch parameters: */
+	int dim;
+	int numberofvertices;
 	iomodel->Constant(&dim,MeshDimensionEnum);
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
@@ -29,5 +23,5 @@
 
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
@@ -38,5 +32,5 @@
 	CreateSingleNodeToElementConnectivity(iomodel);
 
-	for (i=0;i<numberofvertices;i++){
+	for(int i=0;i<numberofvertices;i++){
 		if((iomodel->my_vertices[i]==1)){
 			if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp	(revision 13975)
@@ -20,12 +20,9 @@
 	int    numberofvertices;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-	
 	/*Fetch parameters: */
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
@@ -40,5 +37,5 @@
 
 		if(iomodel->my_vertices[i]){
-			
+
 			/*Add node to nodes dataset: */
 			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,MeltingAnalysisEnum));
Index: /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp	(revision 13975)
@@ -55,5 +55,5 @@
 	iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
 	iomodel->FetchDataToInput(elements,PressureEnum);
-	
+
 	/*Free data: */
 	iomodel->DeleteData(1,MeshElementsEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp	(revision 13975)
@@ -20,6 +20,6 @@
 
 	int   i,analysis_type,dim,verbose;
-	bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy,autodiff;
-	
+	bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy;
+
 	/*output: */
 	Elements    *elements    = NULL;
@@ -31,5 +31,4 @@
 	Parameters  *parameters  = NULL;
 
-	
 	/*Initialize IoModel from input file*/
 	IoModel* iomodel = new IoModel(IOMODEL);
@@ -43,10 +42,4 @@
 	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);
@@ -73,5 +66,5 @@
 		if(solution_type==SteadystateSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
 		if(solution_type==SteadystateSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
-	
+
 		if(VerboseMProcessor()) _pprintLine_("   creating datasets for analysis " << EnumToStringx(analysis_type));
 		CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,rootpath,solution_type,analysis_type,nummodels,i);
Index: /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h	(revision 13975)
@@ -109,5 +109,4 @@
 void  UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints);
 
-
 /*Distribution of dofs: */
 void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type);
Index: /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 
 void  NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel, bool continuous){
-	
+
 	/*First thing, this is a new partition for a new analysis_type, therefore, to avoid a leak, erase the nodes partition that might come through pmy_nodes: */
 	xDelete<bool>(*pmy_nodes);
@@ -51,5 +51,4 @@
 }
 
-
 void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
 
@@ -62,5 +61,5 @@
 	 * the nodes and the vertices. The vertices are similar to continuous galerkin, but the nodes partitioning involves edges, which mess up sorting of 
 	 * ids. */
-	
+
 	int i,j;
 	int    dim;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp	(revision 13975)
@@ -10,14 +10,10 @@
 void	CreateConstraintsPrognostic(Constraints** pconstraints, IoModel* iomodel){
 
+	/*Fetch parameters: */
 	int stabilization;
-	
-	/*Fetch parameters: */
 	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
 
-	/*Output*/
-	Constraints *constraints = NULL;
-
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp	(revision 13975)
@@ -23,7 +23,4 @@
 	int numberofelements;
 
-	/*DataSet*/
-	Loads*    loads    = NULL;
-	
 	/*Fetch parameters: */
 	iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
@@ -32,5 +29,5 @@
 
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp	(revision 13975)
@@ -26,7 +26,4 @@
 	int    stabilization;
 
-	/*DataSets: */
-	Nodes*    nodes = NULL;
-
 	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
@@ -36,5 +33,5 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp	(revision 13975)
@@ -73,4 +73,6 @@
 	if(issmbgradients){
 	        iomodel->FetchDataToInput(elements,SurfaceforcingsHcEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsHrefEnum);
+	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum);
 	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMaxEnum);
 	        iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMinEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp	(revision 13975)
@@ -14,5 +14,4 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 #include "./ModelProcessorx.h"
-
 
 void SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters){
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp	(revision 13975)
@@ -13,9 +13,6 @@
 void	CreateConstraintsSurfaceSlope(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Output*/
-	Constraints* constraints = NULL;
-	
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp	(revision 13975)
@@ -13,9 +13,6 @@
 void	CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel){
 
-	/*DataSet*/
-	Loads*    loads    = NULL;
-
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Create loads if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp	(revision 13975)
@@ -16,10 +16,6 @@
 
 	/*Intermediary*/
-	int i;
 	bool continuous_galerkin=true;
 	int    numberofvertices;
-
-	/*DataSets: */
-	Nodes*    nodes = NULL;
 
 	/*Fetch parameters: */
@@ -27,19 +23,18 @@
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
 	if(!nodes) nodes = new Nodes();
-	
+
 	/*Continuous Galerkin partition of nodes: */
 	NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
-	
+
 	/*First fetch data: */
 	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
 
-	for (i=0;i<numberofvertices;i++){
+	for(int i=0;i<numberofvertices;i++){
+		if(iomodel->my_vertices[i]){
 
-		if(iomodel->my_vertices[i]){
-			
 			/*Add node to nodes dataset: */
 			nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,SurfaceSlopeAnalysisEnum));
@@ -50,5 +45,5 @@
 	/*Clean fetched data: */
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp	(revision 13975)
@@ -37,10 +37,10 @@
 	iomodel->FetchDataToInput(elements,BedEnum);
 	iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
-	
+
 	if (dim==3){
 		iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
 		iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
 	}
-	
+
 	/*Free data: */
 	iomodel->DeleteData(1,MeshElementsEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp	(revision 13975)
@@ -14,17 +14,10 @@
 void	CreateConstraintsThermal(Constraints** pconstraints, IoModel* iomodel){
 
-	/*Intermediary*/
-	int i;
-	int count;
+	/*Fetch parameters: */
 	int    dim;
-	
-	/*Output*/
-	Constraints* constraints = NULL;
-
-	/*Fetch parameters: */
 	iomodel->Constant(&dim,MeshDimensionEnum);
 
 	/*Recover pointer: */
-	constraints=*pconstraints;
+	Constraints* constraints=*pconstraints;
 
 	/*Create constraints if they do not exist yet*/
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp	(revision 13975)
@@ -17,11 +17,8 @@
 	int    dim;
 	int    numberofvertices;
-
-	/*DataSet*/
-	Loads*    loads    = NULL;
 	Pengrid*    pengrid  = NULL;
 
 	/*Recover pointer: */
-	loads=*ploads;
+	Loads* loads=*ploads;
 
 	/*Fetch parameters: */
@@ -40,5 +37,5 @@
 
 	for (i=0;i<numberofvertices;i++){
-	
+
 		/*keep only this partition's nodes:*/
 		if((iomodel->my_vertices[i]==1)){
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp	(revision 13975)
@@ -16,16 +16,12 @@
 
 	/*Intermediary*/
-	int i;
 	bool continuous_galerkin=true;
-	int    numberofvertices;
-
-	/*DataSets: */
-	Nodes*    nodes = NULL;
 
 	/*Fetch parameters: */
+	int    numberofvertices;
 	iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
 
 	/*Recover pointer: */
-	nodes=*pnodes;
+	Nodes* nodes=*pnodes;
 
 	/*Create nodes if they do not exist yet*/
@@ -38,6 +34,5 @@
 	iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
 
-	for (i=0;i<numberofvertices;i++){
-
+	for(int i=0;i<numberofvertices;i++){
 		if(iomodel->my_vertices[i]){
 			/*Add node to nodes dataset: */
@@ -49,5 +44,5 @@
 	/*Clean fetched data: */
 	iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
-	
+
 	/*Assign output pointer: */
 	*pnodes=nodes;
Index: /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp	(revision 13975)
@@ -60,5 +60,5 @@
 	iomodel->FetchDataToInput(elements,VyEnum);
 	iomodel->FetchDataToInput(elements,VzEnum);
-	
+
 	if(dakota_analysis){
 		elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
Index: /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp
===================================================================
--- /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp	(revision 13975)
@@ -26,5 +26,4 @@
 	constraints=*pconstraints;
 
-
 	if(nodes) iomodel->nodecounter=nodes->NumberOfNodes();
 	else iomodel->nodecounter=0;
@@ -32,5 +31,5 @@
 	if(loads)iomodel->loadcounter=loads->NumberOfLoads();
 	else iomodel->loadcounter=0;
-	
+
 	if(constraints)iomodel->constraintcounter=constraints->NumberOfConstraints();
 	else iomodel->constraintcounter=0;
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units){
 
-	extern int my_rank;
+	int my_rank;
 	int i;
 	int index;
@@ -21,4 +21,7 @@
 	int cpu_found;
 
+	/*Get my_rank:*/
+	my_rank=IssmComm::GetRank();
+
 	/*retrieve element we are interested in: */
 	parameters->FindParam(&index,IndexEnum);
@@ -27,5 +30,5 @@
 	 *element, figure out  if they hold the vertex, and the data. If so, return it: */
 	for(i=0;i<elements->Size();i++){
-		Element* element=(Element*)elements->GetObjectByOffset(i);
+		Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		found=element->NodalValue(&value,index,natureofdataenum,process_units);
 		if (found){
@@ -37,5 +40,5 @@
 	/*Broadcast whether we found the element: */
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
+	MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
 	if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
 	#endif
@@ -43,6 +46,6 @@
 	/*Broadcast and plug into response: */
 	#ifdef _HAVE_MPI_
-	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
-	MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,MPI_COMM_WORLD); 
+	MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
+	MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm()); 
 	#else
 	value=cpu_found;
Index: /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h
===================================================================
--- /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 13974)
+++ /issm/trunk/src/c/modules/NodalValuex/NodalValuex.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _NODALVALUEX_H */
-
Index: /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp	(revision 13975)
@@ -34,6 +34,4 @@
 	double* connectivity=NULL;
 
-
-
 	/*Allocate connectivity: */
 	connectivity=xNewZeroInit<double>(nods*width);
@@ -46,10 +44,10 @@
 
 		for(i=0;i<3;i++){
-		
+
 			node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
 			index=node-1;
 
 			num_elements=(int)*(connectivity+width*index+maxels); //retrieve number of elements already  plugged into the connectivity of this node.
-			
+
 			already_plugged=0;
 			for(j=0;j<num_elements;j++){
@@ -64,5 +62,5 @@
 			*(connectivity+width*index+num_elements)=element;
 			*(connectivity+width*index+maxels)=(double)(num_elements+1);
-			
+
 		}
 	}
Index: /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.h
===================================================================
--- /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.h	(revision 13975)
@@ -10,3 +10,2 @@
 
 #endif  /* _NODECONNECTIVITYX_H */
-
Index: /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp	(revision 13975)
@@ -14,6 +14,5 @@
 	int noerr=1;
 	int found=0;
-	int i;
-	
+
 	/*Do we have any nodes for this analysis type? :*/
 	if(nodes->NumberOfNodes(configuration_type)){ 
Index: /issm/trunk/src/c/modules/Orthx/Orthx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Orthx/Orthx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Orthx/Orthx.cpp	(revision 13975)
@@ -6,10 +6,10 @@
 
 void	Orthx( Vector<IssmDouble>** pnewgradj, Vector<IssmDouble>* gradj, Vector<IssmDouble>* oldgradj){
-	
+
 	/*output: */
 	Vector<IssmDouble>* newgradj=NULL;
 
 	/*intermediary:*/
-	IssmDouble norm_new,norm_old,dot_product;;
+	IssmDouble norm_old,dot_product;;
 
 	/*Initialize output*/
Index: /issm/trunk/src/c/modules/Orthx/Orthx.h
===================================================================
--- /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Orthx/Orthx.h	(revision 13975)
@@ -14,3 +14,2 @@
 
 #endif  /* _ORTHX_H */
-
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp	(revision 13975)
@@ -15,8 +15,8 @@
 #include "../../io/io.h"
 #include "../../classes/objects/objects.h"
-		
+
 void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results* results){
 
-	extern int  my_rank;
+	int         my_rank;
 	FILE       *fid                     = NULL;
 	char       *outputfilename          = NULL;
@@ -26,7 +26,10 @@
 	char*       solutiontypestring      = NULL;
 	bool        dakota_analysis         = false;
-	
+
 	/*retrieve parameters: */
 	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	if(dakota_analysis){
@@ -51,5 +54,5 @@
 	/*Now, open file for writing, if not already done: */
 	if(!parameters->Exist(OutputFilePointerEnum)){
-		
+
 		/*We don't have a file pointer. Retrieve the output file name and open it for writing:*/
 		parameters->FindParam(&outputfilename,OutputfilenameEnum);
@@ -69,5 +72,5 @@
 		}
 		xDelete<char>(outputfilename);
-		
+
 		/*Add file pointer in parameters for further calls to OutputResultsx: */
 		parameters->SetParam(fid,OutputFilePointerEnum);
Index: /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h
===================================================================
--- /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h	(revision 13975)
@@ -17,3 +17,2 @@
 
 #endif  /* _OUTPUTRESULTS_H */
-
Index: /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp	(revision 13975)
@@ -17,5 +17,5 @@
 
 	/*Allocate grad_g: */
-	riftproperties=NewVec(numrifts);
+	riftproperties=NewVec(numrifts,IssmComm::GetComm());
 
 	/*Compute rift properties : */
Index: /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h
===================================================================
--- /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h	(revision 13975)
@@ -12,3 +12,2 @@
 
 #endif  /* _OUTPUTRIFTSX_H */
-
Index: /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp	(revision 13975)
@@ -23,5 +23,5 @@
 
 	char line [1000];
-	extern int my_rank;
+	int my_rank;
 	int i;
 
@@ -34,4 +34,7 @@
 	char* catstring=NULL;
 	int   stringlength;
+
+	/*Get my_rank:*/
+	my_rank=IssmComm::GetRank();
 
 	if(my_rank==0){
@@ -56,11 +59,11 @@
 		numanalyses=0;
 		while ( fgets(line, sizeof line, fid) ){
-		
+
 			/*skip comments and empty lines: */
 			if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
-		
+
 			/*Get rid of end of line: */
 			line[strlen(line)-1]='\0';
-		
+
 			if (line[0]=='+'){ /*this is the analysis line: */
 				analyses[numanalyses]=StringToEnumx(&line[1]);  //skip the '+'
@@ -96,10 +99,10 @@
 	/*Ok, broadcast to other cpus: */
  	#ifdef _HAVE_MPI_
-	MPI_Bcast(&numanalyses,1,MPI_INT,0,MPI_COMM_WORLD);
+	MPI_Bcast(&numanalyses,1,MPI_INT,0,IssmComm::GetComm());
 	if(my_rank!=0){
 		analyses=xNew<IssmPDouble>(numanalyses);
 		strings=xNew<char*>(numanalyses);
 	}
-	MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,IssmComm::GetComm());
 	#endif
 	for(i=0;i<numanalyses;i++){
@@ -110,7 +113,7 @@
 		if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
 		#ifdef _HAVE_MPI_
-		MPI_Bcast(&stringlength,1,MPI_INT,0,MPI_COMM_WORLD);
+		MPI_Bcast(&stringlength,1,MPI_INT,0,IssmComm::GetComm());
 		if(my_rank!=0)string=xNew<char>(stringlength);
-		MPI_Bcast(string,stringlength,MPI_CHAR,0,MPI_COMM_WORLD);
+		MPI_Bcast(string,stringlength,MPI_CHAR,0,IssmComm::GetComm());
 		if(my_rank!=0)strings[i]=string;
 		#endif
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h	(revision 13975)
@@ -2,5 +2,4 @@
 	PointCloudFindNeighborsx.h
 */
-
 
 #ifndef _POINTCLOUDFLAGNEIGHBORSX_H
@@ -26,5 +25,3 @@
 void* PointCloudFindNeighborsxt(void* vPointCloudFindNeighborsThreadStruct);
 
-
 #endif /* _POINTCLOUDFLAGNEIGHBORSX_H */
-
Index: /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp
===================================================================
--- /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp	(revision 13975)
@@ -24,5 +24,5 @@
 	my_thread=handle->id;
 	num_threads=handle->num;
-	
+
 	/*recover parameters :*/
 	x=gate->x;
@@ -57,5 +57,5 @@
 			if (j==i)continue;
 			distance=sqrt(pow(x[i]-x[j],2)+ pow(y[i]-y[j],2));
-			
+
 			if(distance<=mindistance){
 
@@ -74,5 +74,5 @@
 	/*Free ressources:*/
 	xDelete<bool>(already);
-	
+
 	return NULL;
 }
Index: /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp	(revision 13975)
@@ -35,12 +35,12 @@
   IssmDouble PDup, PDCUT = 2.0;    // PDcut: rain/snow cutoff temperature (C)
   IssmDouble tstar; // monthly mean surface temp
-  
+
   IssmDouble* pdds=NULL; 
   IssmDouble* pds=NULL; 
   Element* element = NULL;
-  
+
   pdds=xNew<IssmDouble>(NPDMAX+1); 
   pds=xNew<IssmDouble>(NPDCMAX+1); 
-  
+
   // initialize PDD (creation of a lookup table)
   tstep = 0.1;
@@ -55,5 +55,5 @@
 
   itm = reCast<int,IssmDouble>((2*siglim/DT + 1.5));
-  
+
   if (itm >= NPDMAX){
     _printLine_("increase NPDMAX in massBalance.cpp");
@@ -73,5 +73,5 @@
   }
   pdds[itm+1] = siglim + DT;
-  
+
   //*********compute PD(T) : snow/precip fraction. precipitation falling as snow
   tstepc = 0.1;
@@ -100,7 +100,7 @@
   pds[itm+1] = 0.;
   //     *******END initialize PDD
-  
+
   for(i=0;i<elements->Size();i++){
-    element=(Element*)elements->GetObjectByOffset(i);
+    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     element->PositiveDegreeDay(pdds,pds,signorm);
   }
@@ -108,4 +108,4 @@
   xDelete<IssmDouble>(pdds);
   xDelete<IssmDouble>(pds);
-  
+
 }
Index: /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp
===================================================================
--- /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp	(revision 13975)
@@ -15,5 +15,4 @@
 	RecursivePropagation(pool, connectivity,index, flags);
 }
-
 
 void RecursivePropagation(double* pool, double* connectivity, int index, double* flags){
Index: /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h
===================================================================
--- /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h	(revision 13975)
@@ -11,3 +11,2 @@
 
 #endif  /* _PROPAGATEFLAGSFROMCONNECTIVITYX_H */
-
Index: /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp	(revision 13975)
@@ -20,5 +20,5 @@
 	int         global_m,global_n;
 	bool        fromlocalsize = true;
-	int         verbose;
+	bool        oldalloc  = false;
 
 	if(VerboseModule()) _pprintLine_("   Dirichlet lifting applied to load vector");
@@ -32,5 +32,9 @@
 		/*pf = pf - Kfs * y_s;*/
 		Kfs->GetLocalSize(&Kfsm,&Kfsn);
-		Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
+		if(oldalloc)
+		 Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
+		else
+		 Kfsy_s=new Vector<IssmDouble>(Kfsm,global_m);
+
 		if (flag_ys0){
 
@@ -49,5 +53,4 @@
 	}
 
-
 	/*Free ressources and return*/
 	xdelete(&y_s0);
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp	(revision 13975)
@@ -5,5 +5,5 @@
 
 #include "./Reducevectorgtofx.h"
- 
+
 void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters){
 
@@ -12,12 +12,16 @@
 
 	/*variables: */
-	int i;
-	int configuration_type;
-	int fsize;
-	IssmDouble* ug_serial=NULL;
+	int         configuration_type;
+	int         fsize;
+	IssmDouble *ug_serial = NULL;
+	bool        oldalloc  = false;
 
 	/*first figure out fsize: */
 	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
 	fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
+
+	int    analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	int flocalsize = nodes->NumberOfDofsLocal(analysis_type,FsetEnum);
 
 	if(fsize==0){
@@ -26,5 +30,8 @@
 	else{
 		/*allocate: */
-		uf=new Vector<IssmDouble>(fsize);
+		if(oldalloc)
+		 uf=new Vector<IssmDouble>(fsize);
+		else
+		 uf=new Vector<IssmDouble>(flocalsize,fsize);
 
 		if(nodes->NumberOfNodes(configuration_type)){ 
@@ -34,5 +41,5 @@
 
 			/*Go through all nodes, and ask them to retrieve values from ug, and plug them into uf: */
-			for(i=0;i<nodes->Size();i++){
+			for(int i=0;i<nodes->Size();i++){
 
 				Node* node=(Node*)nodes->GetObjectByOffset(i);
Index: /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _REDUCEVECTORGTOFX_H */
-
Index: /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp	(revision 13975)
@@ -21,4 +21,10 @@
 	ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
 
+	int analysis_type;
+	parameters->FindParam(&analysis_type,AnalysisTypeEnum);
+	int slocalsize = nodes->NumberOfDofsLocal(analysis_type,SsetEnum);
+
+	bool oldalloc = false;
+
 	if(ssize==0){
 		ys=NULL;
@@ -26,5 +32,8 @@
 	else{
 		/*allocate: */
-		ys=new Vector<IssmDouble>(ssize);
+		if(oldalloc)
+		 ys=new Vector<IssmDouble>(ssize);
+		else
+		 ys=new Vector<IssmDouble>(slocalsize,ssize);
 
 		if(nodes->NumberOfNodes(configuration_type)){ 
Index: /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h
===================================================================
--- /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _REDUCEVECTORGTOSX_H */
-
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp	(revision 13975)
@@ -12,9 +12,4 @@
 
 void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
-
-	int i;
-
-	extern int num_procs;
-	extern int my_rank;
 
 	/*output: */
Index: /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h
===================================================================
--- /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h	(revision 13975)
@@ -14,3 +14,2 @@
 
 #endif  /* _RESETCONSTRAINTSX_H */
-
Index: /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp	(revision 13975)
@@ -13,5 +13,5 @@
 
 	for (int i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		element->ResetCoordinateSystem();
 	}
Index: /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->RheologyBbarAbsGradient(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/Scotchx/Scotchx.h
===================================================================
--- /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Scotchx/Scotchx.h	(revision 13975)
@@ -5,5 +5,4 @@
 #ifndef _SCOTCHX_H
 #define _SCOTCHX_H
-
 
 #undef __FUNCT__ 
Index: /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp	(revision 13975)
@@ -29,5 +29,5 @@
 
 void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector){
-	
+
 	IssmDouble* serial_vector=NULL;
 
Index: /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp	(revision 13975)
@@ -15,5 +15,5 @@
 
 	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
-	
+
 	double  cm,sp;
 
@@ -33,5 +33,5 @@
 
 	#ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
-	
+
 	int     i,j,k,iret=0;
 	int     lwidth=1;
@@ -611,3 +611,2 @@
 	#endif
 }
-
Index: /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp	(revision 13975)
@@ -18,9 +18,9 @@
 
   int    i;
-  
+
   Element* element = NULL;
-  
+
   for(i=0;i<elements->Size();i++){
-    element=(Element*)elements->GetObjectByOffset(i);
+    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     element->SmbGradients();
   }
Index: /issm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
 #endif
-        
+
 void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){
 
@@ -62,12 +62,12 @@
 		}
 		VecRestoreArray(df,&df_local);
-		
+
 		/*Create indices sets: */
 		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-		ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,&isp);
-		ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,&isv);
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,&isv);
 		#else
-		ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
-		ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
+		ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
+		ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
 		#endif
 	}
Index: /issm/trunk/src/c/modules/Solverx/Solverx.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.cpp	(revision 13975)
@@ -15,7 +15,4 @@
 
 void	Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters){
-
-	/*Intermediary: */
-	int analysis_type;
 
 	/*output: */
Index: /issm/trunk/src/c/modules/Solverx/Solverx.h
===================================================================
--- /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/Solverx/Solverx.h	(revision 13975)
@@ -27,5 +27,5 @@
 void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
 
-#ifdef _HAVE_ADOLC_
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
 void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
 // call back functions:
@@ -38,3 +38,2 @@
 
 #endif  /* _SOLVERX_H */
-
Index: /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp	(revision 13975)
@@ -20,5 +20,5 @@
 	Vec uf0_vector = NULL;
 	Vec df_vector  = NULL;
-	
+
 	if(uf0) uf0_vector = uf0->vector;
 	if(df)  df_vector  = df->vector;
@@ -36,5 +36,4 @@
 	/*Intermediary: */
 	int        local_m,local_n,global_m,global_n;
-	int        analysis_type;
 
 	/*Solver */
@@ -70,5 +69,5 @@
 	MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_m);
 	if(!global_n){
-		*puf=NewVec(0); return;
+		*puf=NewVec(0,IssmComm::GetComm()); return;
 	}
 
@@ -86,5 +85,5 @@
 	}
 	else{
-		MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,fromlocalsize);
+		MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,IssmComm::GetComm(),fromlocalsize);
 	}
 
@@ -102,5 +101,5 @@
 
 	/*Prepare solver*/
-	KSPCreate(MPI_COMM_WORLD,&ksp);
+	KSPCreate(IssmComm::GetComm(),&ksp);
 	KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
 	KSPSetFromOptions(ksp);
@@ -148,5 +147,5 @@
 	if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
 	KSPSolve(ksp,pf,uf);
-	
+
 	/*Check convergence*/
 	KSPGetIterationNumber(ksp,&iteration_number);
@@ -155,5 +154,5 @@
 	/*Free resources:*/
 	KSPFree(&ksp);
-		
+
 	/*Assign output pointers:*/
 	*puf=uf;
Index: /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp
===================================================================
--- /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp	(revision 13975)
@@ -12,4 +12,5 @@
 #include "./Solverx.h"
 #include "../../shared/shared.h"
+#include "../../classes/classes.h"
 #include "../../include/include.h"
 #include "../../io/io.h"
@@ -19,13 +20,9 @@
 #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;
+	int M,N,N2;
 	SeqVec<IssmDouble> *uf = NULL;
 
@@ -35,6 +32,8 @@
 	if(N!=N2)_error_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
 	if(M!=N)_error_("Stiffness matrix should be square!");
+#ifdef _HAVE_ADOLC_
+	ensureContiguousLocations(N);
+#endif
 	IssmDouble *x  = xNew<IssmDouble>(N);
-
 #ifdef _HAVE_ADOLC_
 	SolverxSeq(x,Kff->matrix,pf->vector,N,parameters);
@@ -69,96 +68,139 @@
 #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;
+	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;
+	//  for (int i=0; i<m*m; ++i) std::cout << "EDF_fos_forward_for_solverx A["<< i << "]=" << inVal[i] << std::endl;
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx b["<< i << "]=" << inVal[i+m*m] << std::endl;
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	//  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx x["<< i << "]=" << outVal[i] << std::endl;
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	// compute the RHS
+	double* r=xNew<double>(m);
+	for (int i=0; i<m; i++) {
+		r[i]=inDeriv[m*m+i]; // this is db[i]
+		for (int j=0;j<m; j++) {
+			r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
+		}
+	}
+	gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+	xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
 } /*}}}*/
 int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
 #ifdef _HAVE_GSL_
-  // the matrix will be modified by LU decomposition. Use gsl_A copy
-  double* Acopy = xNew<double>(m*m);
-  xMemCpy(Acopy,inVal,m*m);
-  /*Initialize gsl matrices and vectors: */
-  gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
-  gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
-  gsl_permutation *perm_p = gsl_permutation_alloc (m);
-  int  signPerm;
-  // factorize
-  gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
-  gsl_vector *gsl_x_p = gsl_vector_alloc (m);
-  // solve for the value
-  gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
-  /*Copy result*/
-  xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
-  gsl_vector_free(gsl_x_p);
-  // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
-  double* r=xNew<double>(m);
-  gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
-  for (int dir=0;dir<directionCount;++dir) {
-    // compute the RHS
-    for (int i=0; i<m; i++) {
-      r[i]=inDeriv[m*m+i][dir]; // this is db[i]
-      for (int j=0;j<m; j++) {
-        r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
-      }
-    }
-    gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
-    gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
-    // reuse r
-    xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
-    for (int i=0; i<m; i++) {
-      outDeriv[i][dir]=r[i];
-    }
-  }
-  gsl_vector_free(gsl_dx_p);
-  xDelete(r);
-  gsl_permutation_free(perm_p);
-  xDelete(Acopy);
-  #endif
-  return 0;
-}
-/*}}}*/
-int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z) { /*{{{*/
-  return 0;
+	// the matrix will be modified by LU decomposition. Use gsl_A copy
+	double* Acopy = xNew<double>(m*m);
+	xMemCpy(Acopy,inVal,m*m);
+	/*Initialize gsl matrices and vectors: */
+	gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
+	gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int  signPerm;
+	// factorize
+	gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
+	gsl_vector *gsl_x_p = gsl_vector_alloc (m);
+	// solve for the value
+	gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
+	/*Copy result*/
+	xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
+	gsl_vector_free(gsl_x_p);
+	// solve for the derivatives acc. to A * dx = r  with r=db - dA * x
+	double* r=xNew<double>(m);
+	gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
+	for (int dir=0;dir<directionCount;++dir) {
+		// compute the RHS
+		for (int i=0; i<m; i++) {
+			r[i]=inDeriv[m*m+i][dir]; // this is db[i]
+			for (int j=0;j<m; j++) {
+				r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
+			}
+		}
+		gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
+		gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
+		// reuse r
+		xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
+		for (int i=0; i<m; i++) {
+			outDeriv[i][dir]=r[i];
+		}
+	}
+	gsl_vector_free(gsl_dx_p);
+	xDelete(r);
+	gsl_permutation_free(perm_p);
+	xDelete(Acopy);
+#endif
+	return 0;
+}
+/*}}}*/
+int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	// the adjoint of the solution is our right-hand side
+	gsl_vector_view x_bar=gsl_vector_view_array(dp_U,m);
+	// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+	gsl_vector_view b_bar=gsl_vector_view_array(dp_Z+m*m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+	// now do the adjoint of the matrix
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dp_Z[i*m+j]-=dp_Z[m*m+i]*dp_y[j];
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
+}
+/*}}}*/
+int EDF_fov_reverse_for_solverx(int m, int p, double **dpp_U, int n, double **dpp_Z, double* dp_x, double* dp_y) { /*{{{*/
+	// copy to transpose the matrix
+	double* transposed=xNew<double>(m*m);
+	for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
+	gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
+	gsl_permutation *perm_p = gsl_permutation_alloc (m);
+	int permSign;
+	gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
+	for (int weightsRowIndex=0;weightsRowIndex<p;++weightsRowIndex) {
+		// the adjoint of the solution is our right-hand side
+		gsl_vector_view x_bar=gsl_vector_view_array(dpp_U[weightsRowIndex],m);
+		// the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
+		gsl_vector_view b_bar=gsl_vector_view_array(dpp_Z[weightsRowIndex]+m*m,m);
+		gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
+		// now do the adjoint of the matrix
+		for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dpp_Z[weightsRowIndex][i*m+j]-=dpp_Z[weightsRowIndex][m*m+i]*dp_y[j];
+	}
+	gsl_permutation_free(perm_p);
+	xDelete(transposed);
+	return 0;
 }
 /*}}}*/
 void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
 	// pack inputs to conform to the EDF-prescribed interface
+        // ensure a contiguous block of locations:
+        ensureContiguousLocations(n*(n+1));
         IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
         for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
@@ -170,4 +212,5 @@
 	             n*(n+1), pdoubleEDFin, adoubleEDFin,
 	             n, pdoubleEDFout,X);
+	// for(int i=0; i<n;  i++) {ADOLC_DUMP_MACRO(X[i]);}
 	xDelete(adoubleEDFin);
 	xDelete(pdoubleEDFin);
@@ -181,7 +224,8 @@
 	int              s;
 	gsl_matrix_view  a;
-	gsl_vector_view  b;
-	gsl_vector      *x = NULL;
+	gsl_vector_view  b,x;
 	gsl_permutation *p = NULL;
+//	for (int i=0; i<n*n; ++i) std::cout << "SolverxSeq A["<< i << "]=" << A[i] << std::endl;
+//	for (int i=0; i<n; ++i) std::cout << "SolverxSeq b["<< i << "]=" << B[i] << std::endl;
 	/*A will be modified by LU decomposition. Use copy*/
 	double* Acopy = xNew<double>(n*n);
@@ -191,22 +235,15 @@
 	a = gsl_matrix_view_array (Acopy,n,n);
 	b = gsl_vector_view_array (B,n);
-	x = gsl_vector_alloc (n);
+	x = gsl_vector_view_array (X,n);
 
 	/*Run LU and solve: */
 	p = gsl_permutation_alloc (n);
 	gsl_linalg_LU_decomp (&a.matrix, p, &s);
-	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, x);
-
-	//printf ("x = \n");
-	//gsl_vector_fprintf (stdout, x, "%g");
-
-	/*Copy result*/
-	xMemCpy(X,gsl_vector_ptr(x,0),n);
+	gsl_linalg_LU_solve (&a.matrix, p, &b.vector, &x.vector);
 
 	/*Clean up and assign output pointer*/
 	xDelete(Acopy);
 	gsl_permutation_free(p);
-	gsl_vector_free(x);
-#endif
-}
-/*}}}*/
+#endif
+}
+/*}}}*/
Index: /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp	(revision 13975)
@@ -13,5 +13,5 @@
 
 	for(int i=0;i<constraints->Size();i++){
-	
+
 		Constraint* constraint=(Constraint*)constraints->GetObjectByOffset(i);
 
Index: /issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp
===================================================================
--- /issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp	(revision 13975)
@@ -19,11 +19,23 @@
    if(stage==1){
 	      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,"AutodiffNumDependentObjects")==0) return AutodiffNumDependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectNames")==0) return AutodiffDependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectTypes")==0) return AutodiffDependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjectIndices")==0) return AutodiffDependentObjectIndicesEnum;
+	      else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
 	      else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
+	      else if (strcmp(name,"AutodiffNumIndependentObjects")==0) return AutodiffNumIndependentObjectsEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectNames")==0) return AutodiffIndependentObjectNamesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjectTypes")==0) return AutodiffIndependentObjectTypesEnum;
+	      else if (strcmp(name,"AutodiffIndependentObjects")==0) return AutodiffIndependentObjectsEnum;
 	      else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
 	      else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
-	      else if (strcmp(name,"AutodiffFosForwardOutput")==0) return AutodiffFosForwardOutputEnum;
+	      else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
+	      else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
+	      else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
+	      else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
+	      else if (strcmp(name,"AutodiffMassFluxSegmentsPresent")==0) return AutodiffMassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
 	      else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
 	      else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
@@ -37,4 +49,5 @@
 	      else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
 	      else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
+	      else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
 	      else if (strcmp(name,"DiagnosticAbstol")==0) return DiagnosticAbstolEnum;
 	      else if (strcmp(name,"DiagnosticIcefront")==0) return DiagnosticIcefrontEnum;
@@ -76,4 +89,5 @@
 	      else if (strcmp(name,"HydrologySpcwatercolumn")==0) return HydrologySpcwatercolumnEnum;
 	      else if (strcmp(name,"HydrologyStabilization")==0) return HydrologyStabilizationEnum;
+	      else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
 	      else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
 	      else if (strcmp(name,"InversionCostFunction")==0) return InversionCostFunctionEnum;
@@ -124,5 +138,8 @@
 	      else if (strcmp(name,"MeshDimension")==0) return MeshDimensionEnum;
 	      else if (strcmp(name,"MeshEdges")==0) return MeshEdgesEnum;
-	      else if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
+         else stage=2;
+   }
+   if(stage==2){
+	      if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
 	      else if (strcmp(name,"MeshElementonbed")==0) return MeshElementonbedEnum;
 	      else if (strcmp(name,"MeshElementonsurface")==0) return MeshElementonsurfaceEnum;
@@ -138,8 +155,5 @@
 	      else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
 	      else if (strcmp(name,"MeshVertexonbed")==0) return MeshVertexonbedEnum;
-         else stage=2;
-   }
-   if(stage==2){
-	      if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
+	      else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
 	      else if (strcmp(name,"MeshX")==0) return MeshXEnum;
 	      else if (strcmp(name,"MeshY")==0) return MeshYEnum;
@@ -152,6 +166,10 @@
 	      else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
 	      else if (strcmp(name,"PrognosticVertexPairing")==0) return PrognosticVertexPairingEnum;
+	      else if (strcmp(name,"PrognosticNumRequestedOutputs")==0) return PrognosticNumRequestedOutputsEnum;
+	      else if (strcmp(name,"PrognosticRequestedOutputs")==0) return PrognosticRequestedOutputsEnum;
 	      else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
-	      else if (strcmp(name,"QmuMassFluxSegments")==0) return QmuMassFluxSegmentsEnum;
+	      else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
+	      else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
+	      else if (strcmp(name,"QmuMassFluxSegmentsPresent")==0) return QmuMassFluxSegmentsPresentEnum;
 	      else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
 	      else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
@@ -188,4 +206,6 @@
 	      else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
 	      else if (strcmp(name,"SurfaceforcingsHc")==0) return SurfaceforcingsHcEnum;
+	      else if (strcmp(name,"SurfaceforcingsHref")==0) return SurfaceforcingsHrefEnum;
+	      else if (strcmp(name,"SurfaceforcingsSmbref")==0) return SurfaceforcingsSmbrefEnum;
 	      else if (strcmp(name,"SurfaceforcingsSmbPosMax")==0) return SurfaceforcingsSmbPosMaxEnum;
 	      else if (strcmp(name,"SurfaceforcingsSmbPosMin")==0) return SurfaceforcingsSmbPosMinEnum;
@@ -241,5 +261,8 @@
 	      else if (strcmp(name,"PrognosticSolution")==0) return PrognosticSolutionEnum;
 	      else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
-	      else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
+         else stage=3;
+   }
+   if(stage==3){
+	      if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
 	      else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
 	      else if (strcmp(name,"SurfaceSlopeXAnalysis")==0) return SurfaceSlopeXAnalysisEnum;
@@ -261,8 +284,5 @@
 	      else if (strcmp(name,"Loads")==0) return LoadsEnum;
 	      else if (strcmp(name,"Materials")==0) return MaterialsEnum;
-         else stage=3;
-   }
-   if(stage==3){
-	      if (strcmp(name,"Nodes")==0) return NodesEnum;
+	      else if (strcmp(name,"Nodes")==0) return NodesEnum;
 	      else if (strcmp(name,"Parameters")==0) return ParametersEnum;
 	      else if (strcmp(name,"Vertices")==0) return VerticesEnum;
@@ -277,4 +297,5 @@
 	      else if (strcmp(name,"DofIndexing")==0) return DofIndexingEnum;
 	      else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
+	      else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
 	      else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
 	      else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
@@ -306,4 +327,5 @@
 	      else if (strcmp(name,"Penta")==0) return PentaEnum;
 	      else if (strcmp(name,"PentaP1Input")==0) return PentaP1InputEnum;
+	      else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
 	      else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
 	      else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
@@ -362,5 +384,8 @@
 	      else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
 	      else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
-	      else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
+         else stage=4;
+   }
+   if(stage==4){
+	      if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
 	      else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
 	      else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
@@ -384,8 +409,5 @@
 	      else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
 	      else if (strcmp(name,"Vz")==0) return VzEnum;
-         else stage=4;
-   }
-   if(stage==4){
-	      if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
+	      else if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
 	      else if (strcmp(name,"VzPattyn")==0) return VzPattynEnum;
 	      else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
@@ -477,4 +499,6 @@
 	      else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
 	      else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
+	      else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
+	      else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
 	      else if (strcmp(name,"PetscOptionsAnalyses")==0) return PetscOptionsAnalysesEnum;
 	      else if (strcmp(name,"PetscOptionsStrings")==0) return PetscOptionsStringsEnum;
@@ -483,5 +507,8 @@
 	      else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
 	      else if (strcmp(name,"Regular")==0) return RegularEnum;
-	      else if (strcmp(name,"Scaled")==0) return ScaledEnum;
+         else stage=5;
+   }
+   if(stage==5){
+	      if (strcmp(name,"Scaled")==0) return ScaledEnum;
 	      else if (strcmp(name,"Separate")==0) return SeparateEnum;
 	      else if (strcmp(name,"Sset")==0) return SsetEnum;
@@ -501,5 +528,5 @@
 	      else if (strcmp(name,"Paterson")==0) return PatersonEnum;
 	      else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
-         else stage=5;
+         else stage=6;
    }
 	/*If we reach this point, the string provided has not been found*/
Index: /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->SurfaceAbsVelMisfit(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 
 void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
-	
+
 	/*Intermediary*/
 	Element* element=NULL;
@@ -20,8 +20,8 @@
 	IssmDouble S=0;
 	IssmDouble S_sum;
-	
+
 	/*Compute gradients: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		S+=element->SurfaceArea();
 	}
@@ -29,6 +29,6 @@
 	/*Sum all J from all cpus of the cluster:*/
 	#ifdef _HAVE_MPI_
- 	MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD); 
+ 	MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,IssmComm::GetComm()); 
 	S=S_sum;
 	#endif
Index: /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _SURFACEAREAX_H */
-
Index: /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp	(revision 13975)
@@ -26,5 +26,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->SurfaceAverageVelMisfit(process_units,weight_index);
 	}
@@ -32,6 +32,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->SurfaceLogVelMisfit(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->SurfaceLogVxVyMisfit(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->SurfaceRelVelMisfit(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->ThicknessAbsMisfit(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->ThicknessAcrossGradient(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp
===================================================================
--- /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp	(revision 13975)
@@ -22,5 +22,5 @@
 	/*Compute Misfit: */
 	for (i=0;i<elements->Size();i++){
-		element=(Element*)elements->GetObjectByOffset(i);
+		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
 		J+=element->ThicknessAlongGradient(process_units,weight_index);
 	}
@@ -28,6 +28,6 @@
 	/*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);
+	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
+	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
 	J=J_sum;
 	#endif
Index: /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 13975)
+++ /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp	(revision 13975)
@@ -0,0 +1,79 @@
+/*!\file:  TriMeshProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./TriMeshProcessRiftsx.h"
+#include "../../classes/RiftStruct.h"
+#include "../../shared/shared.h"
+#include "../../include/include.h"
+#include "../../toolkits/toolkits.h"
+
+void TriMeshProcessRiftsx(double** pindex, int* pnel,double** px,double** py,int* pnods,double** psegments,double** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct){
+
+	/*Output*/
+	int      numrifts,numrifts0;
+	int     *riftsnumsegments     = NULL;
+	double **riftssegments        = NULL;
+	int     *riftsnumpairs        = NULL;
+	double **riftspairs           = NULL;
+	double  *riftstips            = NULL;
+	double **riftspenaltypairs    = NULL;
+	int     *riftsnumpenaltypairs = NULL;
+
+	/*Recover initial mesh*/
+	int     nel            = *pnel;
+	double *index          = *pindex;
+	double *x              = *px;
+	double *y              = *py;
+	int     nods           = *pnods;
+	double *segments       = *psegments;
+	double *segmentmarkers = *psegmentmarkers;
+	int     num_seg        = *pnum_seg;
+
+	/*Intermediary*/
+	int     riftflag;
+
+	/*First, do some fixing on the existing mesh: we do not want any element belonging entirely to the segment list (ie: 
+	 *all the nodes of this element belong to the segments (tends to happen when there are corners: */
+	RemoveCornersFromRifts(&index,&nel,&x,&y,&nods,segments,segmentmarkers,num_seg);
+
+	/*Figure out if we have rifts, and how many: */
+	IsRiftPresent(&riftflag,&numrifts0,segmentmarkers,num_seg);
+
+	if(!riftflag) _error_("No rift present in mesh");
+
+	/*Split mesh*/
+	SplitMeshForRifts(&nel,&index,&nods,&x,&y,&num_seg,&segments,&segmentmarkers);
+
+	/*Order segments so that their normals point outside the domain: */
+	OrderSegments(&segments,num_seg, index,nel);
+
+	/*We do not want to output segments mixed with rift segments: wring out the rifts from the segments, using the 
+	 *segmentmarkerlist:*/
+	SplitRiftSegments(&segments,&segmentmarkers,&num_seg,&numrifts,&riftsnumsegments,&riftssegments,numrifts0,nods,nel);
+
+	/*Using rift segments, associate rift faces in pairs, each pair face representing opposite flanks of the rifts facing one another directly: */
+	PairRiftElements(&riftsnumpairs,&riftspairs,numrifts,riftsnumsegments,riftssegments,x,y);
+
+	/*Order rifts so that they start from one tip, go to the other tip, and back: */
+	OrderRifts(&riftstips,riftssegments,riftspairs,numrifts,riftsnumsegments,x,y,nods,nel);
+
+	/*Create penalty pairs, used by Imp: */
+	PenaltyPairs(&riftspenaltypairs,&riftsnumpenaltypairs,numrifts,riftssegments,riftsnumsegments,riftspairs,riftstips,x,y);
+
+	/*Create Riftstruct*/
+	RiftStruct* riftstruct = new RiftStruct(numrifts,riftsnumsegments,riftssegments,riftsnumpairs,riftspairs,riftsnumpenaltypairs,riftspenaltypairs,riftstips);
+
+	/*Assign output pointers for mesh*/
+	*pnel            = nel;
+	*pindex          = index;
+	*px              = x;
+	*py              = y;
+	*pnods           = nods;
+	*psegments       = segments;
+	*psegmentmarkers = segmentmarkers;
+	*pnum_seg        = num_seg;
+
+	/*Assign output pointers for rifts*/
+	*priftstruct = riftstruct;
+}
Index: /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h
===================================================================
--- /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h	(revision 13975)
+++ /issm/trunk/src/c/modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h	(revision 13975)
@@ -0,0 +1,12 @@
+/*!\file:  TriMeshProcessRiftsx.h
+ * \brief header file for TriMeshProcessRifts module
+ */ 
+
+#ifndef _TRIMESHPROCESSRIFTX_H
+#define _TRIMESHPROCESSRIFTX_H
+
+class RiftStruct;
+
+void TriMeshProcessRiftsx(double** pindex, int* pnel,double** px,double** py,int* pnods,double** psegments,double** psegmentmarkers,int *pnum_seg,RiftStruct **priftstruct);
+
+#endif  /* _TRIMESHPROCESSRIFTX_H*/
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp	(revision 13975)
@@ -11,10 +11,12 @@
 #include "../../EnumDefinitions/EnumDefinitions.h"
 /*ANSI_DECLARATORS needed to call triangle library: */
-#ifndef ANSI_DECLARATORS
-#define ANSI_DECLARATORS
-#include "triangle.h"
-#undef ANSI_DECLARATORS
-#else
-#include "triangle.h"
+#if defined(_HAVE_TRIANGLE_)
+	#ifndef ANSI_DECLARATORS
+	#define ANSI_DECLARATORS
+	#include "triangle.h"
+	#undef ANSI_DECLARATORS
+	#else
+	#include "triangle.h"
+	#endif
 #endif
 /*}}}*/
@@ -22,4 +24,7 @@
 void TriMeshx(SeqMat<IssmPDouble>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<IssmPDouble>** psegments,SeqVec<IssmPDouble>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area){
 
+#if !defined(_HAVE_TRIANGLE_)
+	_error_("triangle has not been installed");
+#else
 	/*indexing: */
 	int i,j;
@@ -76,9 +81,9 @@
 		}
 	}
-	
+
 	/*fill in the point attribute list: */
 	in.pointattributelist = xNew<REAL>(in.numberofpoints*in.numberofpointattributes);
 	for (i=0;i<in.numberofpoints;i++) in.pointattributelist[i] = 0.0;
-	
+
 	/*fill in the point marker list: */
 	in.pointmarkerlist = xNew<int>(in.numberofpoints);
@@ -96,5 +101,5 @@
 		in.numberofsegments+=contour->nods-1;
 	}
-	
+
 	in.segmentlist = xNew<int>(in.numberofsegments*2);
 	in.segmentmarkerlist = xNewZeroInit<int>(in.numberofsegments);
@@ -128,5 +133,5 @@
 		counter++;
 	}
-	
+
 	/*Build regions: */
 	in.numberofregions = 0;
@@ -194,5 +199,5 @@
 	index_matrix=new SeqMat<IssmPDouble>(index,out.numberoftriangles,3,1.0);
 	*pindex=index_matrix;
-	
+
 	segments_matrix=new SeqMat<IssmPDouble>(segments,out.numberofsegments,3,1.0);
 	*psegments=segments_matrix;
@@ -201,3 +206,4 @@
 	*py=new SeqVec<IssmPDouble>(y,out.numberofpoints);
 	*psegmentmarkerlist=new SeqVec<IssmPDouble>(segmentmarkerlist,out.numberofsegments);
+#endif
 }
Index: /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h
===================================================================
--- /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/TriMeshx/TriMeshx.h	(revision 13975)
@@ -6,5 +6,5 @@
 #define _TRIMESHX_H_
 
-#include "string.h"
+#include <string.h>
 #include "../../Container/Container.h"
 #include "../../classes/objects/objects.h"
Index: /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp
===================================================================
--- /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp	(revision 13975)
@@ -24,13 +24,8 @@
 	R2     r;
 	I2     I;
-	int    i,j,k;
-	int    i0,i1,i2;
-	double areacoord[3];
-	double aa,bb;
-	double data_value;
+	int    i;
 	Icoor2 dete[3];
-	int verbose=0;
 
-	// read background mesh 
+	/* read background mesh */
 	Mesh Th(index,x,y,nods,nel); 
 	Th.CreateSingleVertexToTriangleConnectivity();
@@ -40,5 +35,5 @@
 		//Get current point coordinates
 		r.x=x0[i]; r.y=y0[i];
-		
+
 		I=Th.R2ToI2(r);
 
Index: /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp
===================================================================
--- /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 
 void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg){
-	
+
 	int configuration_type;
 	IssmDouble* yg_serial=NULL;
Index: /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp
===================================================================
--- /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/VecMergex/VecMergex.cpp	(revision 13975)
@@ -18,8 +18,7 @@
 	/*retrieve parameters: */
 	parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	
+
 	/*serialize uf: */
 	uf_serial=uf->ToMPISerial();
-
 
 	/*Do we have any nodes for this configuration? :*/
Index: /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 13974)
+++ /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp	(revision 13975)
@@ -11,10 +11,4 @@
 void VerticesDofx( Vertices* vertices, Parameters* parameters) {
 
-	int i;
-
-	int  found=0;
-	extern int num_procs;
-	extern int my_rank;
-	
 	/*intermediary: */
 	int  numberofvertices;
@@ -23,11 +17,11 @@
 	numberofvertices=vertices->NumberOfVertices();
 
-	/*Ensure that only for each cpu, the partition border vertices only will be taken into account once 
-	 * across the cluster. To do so, we flag all the clone vertices: */
+	/*Ensure that only for each cpu, the partition border vertices only will be
+	 * taken into account once across the cluster. To do so, we flag all the
+	 * clone vertices: */
 	vertices->FlagClones(numberofvertices);
 
-	/*Go through all vertices and distribute 1 dof at a time. When a  vertex has already been distributed his dof on a cpu, 
-	 * all other cpus with the same vertex cannot distribute it anymore. Use clone field to be sure of that: */
-	vertices->DistributeDofs(numberofvertices,1); //only 1 dof per vertex.
+	/*Go through all vertices and distribute pids*/
+	vertices->DistributePids(numberofvertices); 
 
 }
Index: /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h
===================================================================
--- /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 13974)
+++ /issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h	(revision 13975)
@@ -13,3 +13,2 @@
 
 #endif  /* _VERTICESDOFX_H */
-
Index: /issm/trunk/src/c/modules/modules.h
===================================================================
--- /issm/trunk/src/c/modules/modules.h	(revision 13974)
+++ /issm/trunk/src/c/modules/modules.h	(revision 13975)
@@ -7,6 +7,4 @@
 
 /*Modules: */
-#include "./AddExternalResultx/AddExternalResultx.h"
-#include "./AutodiffDriversx/AutodiffDriversx.h"
 #include "./AverageFilterx/AverageFilterx.h"
 #include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
@@ -23,7 +21,5 @@
 #include "./ControlInputSetGradientx/ControlInputSetGradientx.h"
 #include "./ControlInputScaleGradientx/ControlInputScaleGradientx.h"
-#include "./CostFunctionx/CostFunctionx.h"
 #include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
-#include "./DakotaResponsesx/DakotaResponsesx.h"
 #include "./Delta18oParameterizationx/Delta18oParameterizationx.h"
 #include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
@@ -38,6 +34,4 @@
 #include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
 #include "./HoleFillerx/HoleFillerx.h"
-#include "./TotalSmbx/TotalSmbx.h"
-#include "./IceVolumex/IceVolumex.h"
 #include "./InputControlUpdatex/InputControlUpdatex.h"
 #include "./InputConvergencex/InputConvergencex.h"
@@ -67,20 +61,7 @@
 #include "./Krigingx/Krigingx.h"
 #include "./Shp2Kmlx/Shp2Kmlx.h"
-#include "./MassFluxx/MassFluxx.h"
-#include "./MaxAbsVxx/MaxAbsVxx.h"
-#include "./MaxAbsVyx/MaxAbsVyx.h"
-#include "./MaxAbsVzx/MaxAbsVzx.h"
-#include "./MaxVelx/MaxVelx.h"
-#include "./ElementResponsex/ElementResponsex.h"
-#include "./MaxVxx/MaxVxx.h"
-#include "./MaxVyx/MaxVyx.h"
-#include "./MaxVzx/MaxVzx.h"
 #include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
 #include "./MeshPartitionx/MeshPartitionx.h"
 #include "./MeshProfileIntersectionx/MeshProfileIntersectionx.h"
-#include "./MinVelx/MinVelx.h"
-#include "./MinVxx/MinVxx.h"
-#include "./MinVyx/MinVyx.h"
-#include "./MinVzx/MinVzx.h"
 #include "./SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
 #include "./SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
@@ -99,13 +80,9 @@
 #include "./PositiveDegreeDayx/PositiveDegreeDayx.h"
 #include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
-#include "./Dakotax/Dakotax.h"
 #include "./Reduceloadx/Reduceloadx.h"
 #include "./Reducevectorgtosx/Reducevectorgtosx.h"
 #include "./Reducevectorgtofx/Reducevectorgtofx.h"
-#include "./RequestedOutputsx/RequestedOutputsx.h"
-#include "./RequestedDependentsx/RequestedDependentsx.h"
 #include "./ResetConstraintsx/ResetConstraintsx.h"
 #include "./ResetCoordinateSystemx/ResetCoordinateSystemx.h"
-#include "./Responsex/Responsex.h"
 #include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
 #include "./Scotchx/Scotchx.h"
@@ -114,15 +91,10 @@
 #include "./SpcNodesx/SpcNodesx.h"
 #include "./SurfaceAreax/SurfaceAreax.h"
-#include "./SystemMatricesx/SystemMatricesx.h"
-#include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
-#include "./TimeAdaptx/TimeAdaptx.h"
 #include "./TriaSearchx/TriaSearchx.h"
 #include "./TriMeshx/TriMeshx.h"
+#include "./TriMeshProcessRiftsx/TriMeshProcessRiftsx.h"
 #include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
-#include "./ThicknessAbsGradientx/ThicknessAbsGradientx.h"
 #include "./ThicknessAlongGradientx/ThicknessAlongGradientx.h"
 #include "./ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
-#include "./UpdateVertexPositionsx/UpdateVertexPositionsx.h"
-#include "./UpdateConstraintsx/UpdateConstraintsx.h"
 #include "./UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h"
 #include "./VerticesDofx/VerticesDofx.h"
Index: /issm/trunk/src/c/shared/Alloc/alloc.cpp
===================================================================
--- /issm/trunk/src/c/shared/Alloc/alloc.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Alloc/alloc.cpp	(revision 13975)
@@ -11,5 +11,4 @@
  * the allocation routines described here do not work.
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -28,5 +27,5 @@
 
 void xdelete(Matrix<IssmDouble>** pv){
-	
+
 	if (pv && *pv){
 		/*There is no mxDelete in the Matlab API -> using delete trips up Matlab. So we 
Index: /issm/trunk/src/c/shared/Alloc/xNewDelete.h
===================================================================
--- /issm/trunk/src/c/shared/Alloc/xNewDelete.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Alloc/xNewDelete.h	(revision 13975)
@@ -8,10 +8,9 @@
 #include <cassert>
 
-
 // memory management of types 
 // T with non-trivial constructors require 
 // C++ style memory management
 #define USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
-// but for speed on may alternatively use C memory managment
+// but for speed on may alternatively use C memory management
 // but can do so safely only for T that are at most 
 // plain old data structures (POD)
@@ -69,4 +68,24 @@
   assert(aT_p);
   return aT_p;
+#endif
+}
+
+template <class T>
+T** xNewZeroInit(unsigned int dim1, unsigned int dim2) {
+#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
+  T** aT_pp=xNew<T>(dim1,dim2);
+  for (unsigned int i=0; i<dim1*dim2;++i)
+    (*aT_pp)[i]=(T)0;
+  return aT_pp;
+#else
+  T* buf=(T*)calloc(dim1*dim2*sizeof(T));
+  assert(buf );
+  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
+  assert(aT_pp );
+  for (unsigned int i=0;i<dim1;++i) {
+    aT_pp [i]=buf;
+    buf+=dim2;
+  }
+  return aT_pp ;
 #endif
 }
@@ -134,3 +153,2 @@
 
 #endif
-
Index: /issm/trunk/src/c/shared/Bamg/shared.h
===================================================================
--- /issm/trunk/src/c/shared/Bamg/shared.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Bamg/shared.h	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: header file for all shared  routines.
  */
-
 
 #ifndef _SHAREDBamg_H_
Index: /issm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp	(revision 13975)
@@ -9,5 +9,4 @@
 	int* ndof_list=NULL;
 	int *doflist = NULL;
-
 
 	if(numnodes){
Index: /issm/trunk/src/c/shared/Elements/GetLocalDofList.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/GetLocalDofList.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/GetLocalDofList.cpp	(revision 13975)
@@ -15,5 +15,4 @@
 		ndof_list=xNew<int>(numnodes);
 		ngdof_list_cumulative=xNew<int>(numnodes);
-
 
 		/*Get number of dofs per node, and total for this given set*/
Index: /issm/trunk/src/c/shared/Elements/Paterson.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/Paterson.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/Paterson.cpp	(revision 13975)
@@ -10,5 +10,5 @@
 
 IssmDouble Paterson(IssmDouble temperature){
-	
+
 	/*output: */
 	IssmDouble B;
@@ -29,5 +29,4 @@
 //	% fittedmodel=fit(Temp,B,'cubicspline');
 //	% B=fittedmodel(temperature);
-
 
 	if(T<=-45.0){
@@ -61,5 +60,5 @@
 		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622487*pow(T+5,3)+0.015290593619213*pow(T+5,2)  -0.048160403003748*(T+5)+  0.854987973338348);
 	}
-	else if(T>=-2.0){
+	else{
 		B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622488*pow(T+2,3)-0.018449844983174*pow(T+2,2)  -0.057638157095631*(T+2)+  0.746900791092860);
 	}
@@ -70,5 +69,2 @@
 	return B;
 }
-
-
-
Index: /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp	(revision 13975)
@@ -10,6 +10,6 @@
   IssmDouble B;    // surface mass balance, melt+accumulation
 
-  int    iqj,imonth, j;
-  
+  int    iqj,imonth;
+
   IssmDouble saccu;     // yearly surface accumulation
   IssmDouble smelt;     // yearly melt
@@ -19,6 +19,5 @@
   IssmDouble runoff; //meltwater only, does not include rain 
   IssmDouble sconv; //rhow_rain/rhoi / 12 months
-  
-  IssmDouble density;
+
   IssmDouble lapser=6.5/1000., sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
   IssmDouble desfac = 0.5;                 // desert elevation factor
@@ -27,5 +26,5 @@
   IssmDouble st;             // elevation between altitude of the temp record and current altitude
   IssmDouble sp;             // elevation between altitude of the prec record and current altitude
-  
+
   // PDD and PD constants and variables
   IssmDouble siglim;          // sigma limit for the integration which is equal to 2.5 sigmanorm
@@ -35,5 +34,5 @@
   IssmDouble DT = 0.02;
   IssmDouble pddt, pd; // pd: snow/precip fraction, precipitation falling as snow
-  
+
   IssmDouble q, qmpt; // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
   IssmDouble qm = 0.;        // snow part of the precipitation 
@@ -42,22 +41,21 @@
   IssmDouble pdd = 0.;     
   IssmDouble frzndd = 0.;  
-  
+
   IssmDouble tstar;          // monthly mean surface temp
   IssmDouble Tsum= 0.;       // average summer (JJA) temperature
   IssmDouble Tsurf = 0.;     // average annual temperature    
-  
 
   IssmDouble deltm=1./12.;
   int    ismon[12]={11,0,1,2,3,4,5,6,7,8,9,10};
-  
+
   IssmDouble snwm;  // snow that could have been melted in a year.
   IssmDouble snwmf; //  ablation factor for snow per positive degree day.
   IssmDouble smf;   //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002).
-  
+
   IssmDouble dfrz=1.5, CovrLm=2009./3.35e+5, dCovrLm=dfrz*CovrLm; //m*J kg^-1 C^-1 /(J kg^-1)=m/C yr
   IssmDouble supice,supcap,diffndd;
   IssmDouble fsupT=0.5,  fsupndd=0.5;  // Tsurf mode factors for supice
   IssmDouble pddtj, hmx2;
-  
+
   sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
 
@@ -68,13 +66,13 @@
   siglim0c = siglimc/DT + 0.5;
   PDup = siglimc+PDCUT;
-  
+
   // seasonal loop
     for (iqj = 0; iqj < 12; iqj++){
       imonth =  ismon[iqj];
-  
+
       st=(s-s0t)/1000.;
       tstar = monthlytemperatures[imonth] - lapser *max(st,sealev);
       Tsurf = tstar*deltm+Tsurf;        
-      
+
       /*********compute PD ****************/
       if (tstar < PDup){
@@ -83,15 +81,15 @@
       else { 
 	pd = 0.;}
-      
+
       /******exp des/elev precip reduction*******/
       sp=(s-s0p)/1000.; // deselev effect is wrt chng in topo
       if (sp>0.0){q = exp(-desfac*sp);}
       else {q = 1.0;}
-      
+
       qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month
       qmpt= q*monthlyprec[imonth]*sconv;           
       qmp= qmp + qmpt;
       qm= qm + qmpt*pd;
-      
+
       /*********compute PDD************/
       // ndd(month)=-(tstar-pdd(month)) since ndd+pdd gives expectation of
@@ -105,10 +103,10 @@
       else{frzndd = frzndd - tstar*deltm; }
   } // end of seasonal loop 
-  
+
   //******************************************************************
     saccu = qm;
     prect = qmp;     // total precipitation during 1 year taking into account des. ef.
     Tsum=Tsum/3;
-    
+
     /***** determine PDD factors *****/
     if(Tsum< -1.) {
@@ -126,10 +124,10 @@
     snwmf=0.95*snwmf;
     smf=0.95*smf;
-    
+
     /*****  compute PDD ablation and refreezing *****/
     pddt = pdd *365;
     snwm = snwmf*pddt;       // snow that could have been melted in a year
     hmx2 = min(h,dfrz);   // refreeze active layer max depth: dfrz
-    
+
     if(snwm < saccu) {
       water=prect-saccu + snwm; //water=rain + snowmelt
@@ -147,7 +145,7 @@
       //     hold the meltwater around for refreezing? And melt-time will have
       //     low seasonal frzndd
-      
+
       //      Superimposed ice :  Pfeffer et al. 1991, Tarasov 2002
-      
+
       supice= min(hmx2*CovrLm*frzndd+2.2*(saccu-snwm), water); // superimposed ice
       supcap=min(2.2*(saccu-snwm),water);
@@ -172,5 +170,5 @@
     //     does supice make sense when H< 0.1m? then d=thermoactive ice layer ////
     //     < 0.1 
-    
+
     //     make more sense to just use residual pdd-ndd except that pdd
     //     residual not clear yet
@@ -197,9 +195,9 @@
     if(Tsurf<0) {
       Tsurf= min(Tsurf+fsupT*diffndd , 0.);}
-    
+
     B = -smelt+saccu;
     B = B/yts;
     pddtj=pddt;
-  
+
   return B;
 }
Index: /issm/trunk/src/c/shared/Elements/PrintArrays.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/PrintArrays.cpp	(revision 13975)
@@ -10,4 +10,21 @@
 		for(int j=0;j<cols;j++) _printString_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
 		_printLine_(" ]");
+	}  
+	_printLine_("");
+}
+void printsparsity(IssmPDouble* array,int lines,int cols){
+	int count;
+	_printLine_("");
+	for(int i=0;i<lines;i++){  
+		_printString_("   [ ");
+		count = 0;
+		for(int j=0;j<cols;j++){
+			if(array[i*cols+j]!=0.0){
+				_printString_( " X"); count++;
+			}
+			else
+			 _printString_( " .");
+		}
+		_printLine_(" ] "<<i<<" => "<<count);
 	}  
 	_printLine_("");
Index: /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp	(revision 13975)
@@ -20,5 +20,5 @@
 void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array){
 
-	int     i,j;
+	int     i;
 	int     numdofs   = 0;
 	IssmDouble *transform = NULL;
Index: /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp
===================================================================
--- /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp	(revision 13975)
@@ -21,5 +21,5 @@
 void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array){
 
-	int     i,j;
+	int     i;
 	int     numdofs   = 0;
 	IssmDouble *transform = NULL;
Index: /issm/trunk/src/c/shared/Elements/elements.h
===================================================================
--- /issm/trunk/src/c/shared/Elements/elements.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Elements/elements.h	(revision 13975)
@@ -40,4 +40,5 @@
 void printarray(IssmPDouble* array,int lines,int cols=1);
 void printarray(int* array,int lines,int cols=1);
+void printsparsity(IssmPDouble* 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 13974)
+++ /issm/trunk/src/c/shared/Exceptions/Exceptions.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 #include "../../include/include.h"
 
-ErrorException::ErrorException(const string &what_arg){
+ErrorException::ErrorException(const string &what_arg){/*{{{*/
 
 	what_str=what_arg;
@@ -18,7 +18,6 @@
 	function_name="";
 	file_line=0;
-}
-
-ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){
+}/*}}}*/
+ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
 
 	what_str=what_arg;
@@ -26,20 +25,18 @@
 	function_name=what_function;
 	file_line=what_line;
-}
+}/*}}}*/
+ErrorException::~ErrorException() throw(){/*{{{*/
+}/*}}}*/
+const char* ErrorException::what() const throw(){/*{{{*/
+	return what_str.c_str();
+}/*}}}*/
+void ErrorException::Report() const{/*{{{*/
 
-ErrorException::~ErrorException() throw(){
-	extern int num_procs;
-	/*We want the report only for matlab modules, otherwise we get twice the report
-	 * We assume that if num_procs==1, it is a module (FIXME)*/
-	if(num_procs==1) this->Report();
-}
+	int my_rank;
+	int num_procs;
 
-const char* ErrorException::what() const throw(){
-	return what_str.c_str();
-}
-
-void ErrorException::Report() const{
-	extern int my_rank;
-	extern int num_procs;
+	/*recover my_rank and num_procs:*/
+	my_rank=IssmComm::GetRank();
+	num_procs=IssmComm::GetSize();
 
 	if (function_name=="" || file_line==0){ //WINDOWS
@@ -48,12 +45,44 @@
 	else{
 		if(num_procs==1){
-			_printLine_("\n??? Error using ==> " << file_name.c_str() << ":" << file_line);
+			_printLine_("\n??? Error in ==> " << file_name.c_str() << ":" << file_line);
 			_printLine_(function_name.c_str() << " error message: " << what() << "\n");
 		}
 		else{
-			_printLine_("\n[" << my_rank << "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
-			_printLine_("[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
+			_printLine_("\n[" << my_rank<< "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
+			_printLine_(  "[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
 		}
 	}
 	return;
-}
+}/*}}}*/
+const char* ErrorException::MatlabReport() const{/*{{{*/
+
+	/*Output*/
+	std::ostringstream buffer;
+
+	if (this->file_line==0){ //WINDOWS
+		 buffer << " error message: " << (this->what_str).c_str();
+	}
+	else{
+		buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
+		buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
+	}
+
+	const string buffer2 = buffer.str();
+	return buffer2.c_str();
+}/*}}}*/
+const char* ErrorException::PythonReport() const{/*{{{*/
+
+	/*Output*/
+	std::ostringstream buffer;
+
+	if (this->file_line==0){ //WINDOWS
+		buffer << " error message: " << (this->what_str).c_str();
+	}
+	else{
+		buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
+		buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
+	}
+
+	const string buffer2 = buffer.str();
+	return buffer2.c_str();
+}/*}}}*/
Index: /issm/trunk/src/c/shared/Exceptions/exceptions.h
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Exceptions/exceptions.h	(revision 13975)
@@ -16,5 +16,5 @@
 /*We derive our classes from the c++ exception class: */
 class ErrorException: public exception {
-	
+
 	string   what_str;
 	string   function_name;
@@ -28,4 +28,6 @@
 	virtual const char *what() const throw();
 	void Report() const;
+	const char* MatlabReport() const;
+	const char* PythonReport() const;
 
 };
Index: /issm/trunk/src/c/shared/Exceptions/exprintf.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exceptions/exprintf.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Exceptions/exprintf.cpp	(revision 13975)
@@ -5,5 +5,4 @@
  * ErrorException(exprintf("%s%i\n","test failed for id:",id));
  */ 
-
 
 #include <stdarg.h>
@@ -17,5 +16,4 @@
 	char *buffer = NULL;
 	int   n,size = 100;
-	int   string_size;
 
 	//variable list of arguments
Index: /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp	(revision 13975)
@@ -12,5 +12,5 @@
 
 int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname){
-	
+
 	/*Error management: */
 	int noerr=1;
@@ -33,8 +33,8 @@
 		fprintf(fid,"%s %s\n","##","Icon:0");
 		fprintf(fid,"%s %s %s %s\n","#","Points","Count","Value");
-		
+
 		/*Write number of profile vertices: */
 		fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
-	
+
 		/*Write next line: */
 		fprintf(fid,"%s %s %s %s %s\n","#","X","pos","Y","pos");
Index: /issm/trunk/src/c/shared/Exp/IsInPoly.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPoly.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Exp/IsInPoly.cpp	(revision 13975)
@@ -18,5 +18,5 @@
 	int i, j, c = 0;
 	double n1, n2, normp, scalar;
-	
+
 	/*first test, are they colinear? if yes, is the point in the middle of the segment*/
 	if (edgevalue != 2 ){
Index: /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp
===================================================================
--- /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp	(revision 13975)
@@ -5,15 +5,12 @@
 #include <math.h>
 
-
 #include "./exp.h"
-
 
 int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){
 
-	int i,j;
 	double x0,y0;
 
 	/*Go through all vertices of the mesh:*/
-	for (i=0;i<nods;i++){
+	for(int i=0;i<nods;i++){
 		if (in[i]){
 			/*this vertex already is inside one of the contours, continue*/
Index: /issm/trunk/src/c/shared/Exp/exp.h
===================================================================
--- /issm/trunk/src/c/shared/Exp/exp.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Exp/exp.h	(revision 13975)
@@ -60,5 +60,5 @@
 template <class doubletype>
 int DomainOutlineRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){
-	
+
 	/*indexing: */
 	int i,counter;
@@ -90,9 +90,9 @@
 	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);
+		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
+		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
+		fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
+		fscanf(fid,"%20u %255s\n",&n,chardummy);
+		fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
 		for (i=0;i<n;i++) fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
 		/*check whether we are at the end of the file, otherwise, keep reading next profile:*/
@@ -100,5 +100,5 @@
 		nprof++;
 	}
-	
+
 	/*Allocate and initialize all the profiles: */
 	profnvertices = xNew<int>(nprof);
@@ -118,18 +118,18 @@
 
 		/*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);
-		
+		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
+		fscanf(fid,"%255s %255s\n",chardummy,chardummy);
+		fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
+
 		/*Get number of profile vertices: */
-		fscanf(fid,"%20u %256s\n",&n,chardummy);
-	
+		fscanf(fid,"%20u %255s\n",&n,chardummy);
+
 		/*Skip next line: */
-		fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
+		fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
 
 		/*Allocate vertices: */
 		x=xNew<doubletype>(n);
 		y=xNew<doubletype>(n);
-		
+
 		/*Read vertices: */
 		for (i=0;i<n;i++){
@@ -170,5 +170,4 @@
 	doubletype         **pprofx        = NULL;
 	doubletype         **pprofy        = NULL;
-	Contour<doubletype> *contour       = NULL;
 
 	/*output: */
Index: /issm/trunk/src/c/shared/MemOps/xMemCpy.h
===================================================================
--- /issm/trunk/src/c/shared/MemOps/xMemCpy.h	(revision 13974)
+++ /issm/trunk/src/c/shared/MemOps/xMemCpy.h	(revision 13975)
@@ -17,3 +17,2 @@
 
 #endif
-
Index: /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/BrentSearch.cpp	(revision 13975)
@@ -40,5 +40,5 @@
 	maxiter=optpars->maxiter;
 	cm_jump=optpars->cm_jump;
-	
+
 	/*initialize counter and get response at the boundaries*/
 	iter=0;
Index: /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp	(revision 13975)
@@ -20,5 +20,5 @@
 	/*output: */
 	IssmDouble eps;
-	
+
 	/*intermediary: */
 	IssmDouble *newvalues     = NULL;
Index: /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp	(revision 13975)
@@ -38,5 +38,5 @@
 	x2       =optpars->xmax;
 	maxiter  =optpars->maxiter;
-	
+
 	//get the value of the function at the first boundary
 	fx1= (*f)(x1,optargs);
Index: /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp	(revision 13975)
@@ -16,5 +16,5 @@
 
 char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){
-	
+
 	/*output: */
 	char*   outstring=NULL;
Index: /issm/trunk/src/c/shared/Numerics/Synchronize.sh
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/Synchronize.sh	(revision 13975)
@@ -2,5 +2,5 @@
 #Synchronize Verbosity
 #first remove existing files
-rm $ISSM_DIR/src/m/shared/Verb*.m
+rm $ISSM_DIR/src/m/classes/Verb*.m
 
 echo "Synchronizing Verbosity levels..."
@@ -50,19 +50,4 @@
 	echo "$FILENAME -> 2^$POWER = $BINARY"
 
-	#Add Verbosity Matlab file{{{
-	cat <<END > $ISSM_DIR"/src/m/shared/"$(echo $FILENAME".m")
-function bool=$(echo $FILENAME)()
-%$(echo $FILENAME | awk {'print toupper($1)'}) - Return true if $(echo $LEVELNAME | awk {'print tolower($1)'}) level is activated
-%
-%   WARNING: DO NOT MODIFY THIS FILE
-%            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
-%            Please read src/c/shared/Numerics/README for more information
-%
-%   Usage:
-%      bool=$FILENAME()
-
-bool=logical(bitand(GetVerbosityLevel(),$BINARY));
-END
-	#}}}
 	#Add case to verbose.m FIELDS{{{
 	if [ $i -eq 1 ]; then cat <<END >> FIELDS
@@ -135,5 +120,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/UnitConversion.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/UnitConversion.cpp	(revision 13975)
@@ -40,9 +40,8 @@
 }
 
-
 IssmDouble UnitConversionScaleFactor(int type_enum){
 
 	IssmDouble yts=365.0*24.0*3600.0;
-	
+
 	IssmDouble scale;
 	switch(type_enum){
@@ -72,4 +71,5 @@
 		case SurfaceforcingsANegEnum:						scale=yts;break;     //m/yr
 		case SurfaceforcingsBNegEnum:						scale=yts;break;     //m/yr
+		case SurfaceforcingsSmbrefEnum:					scale=yts;break;     //m/yr
 		case MisfitEnum:                             scale=pow(yts,2);break; //(m/yr)^2
 		case MassFluxEnum:                           scale=pow((IssmDouble)10,-12)*yts;break; // (GigaTon/year)
Index: /issm/trunk/src/c/shared/Numerics/Verbosity.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/Verbosity.cpp	(revision 13975)
@@ -28,4 +28,5 @@
 bool VerboseControl(void){return (GetVerbosityLevel() & 32);} /* 2^5*/
 bool VerboseQmu(void){return (GetVerbosityLevel() & 64);} /* 2^6*/
+bool VerboseAutodiff(void){return (GetVerbosityLevel() & 128);} /* 2^7*/
 
 /*Verbosity Setup*/
@@ -41,7 +42,5 @@
 /*FUNCTION GetVerbosityLevel {{{*/
 int  GetVerbosityLevel(void){
-
 	_assert_(verbositylevel>=0);
 	return verbositylevel;
-
 }/*}}}*/
Index: /issm/trunk/src/c/shared/Numerics/Verbosity.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/Verbosity.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/Verbosity.h	(revision 13975)
@@ -14,4 +14,5 @@
 bool VerboseControl(void);
 bool VerboseQmu(void);
+bool VerboseAutodiff(void);
 
 /*Setup Verbosity level*/
Index: /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp	(revision 13975)
@@ -7,9 +7,8 @@
 void XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors){
 
-	int		i,j;
 	IssmDouble	x[3],y[3],z[3];
 	IssmDouble	x_norm, y_norm, z_norm;
 
-	for(i=0;i<6;i++){
+	for(int i=0;i<6;i++){
 		if(xIsNan<IssmDouble>(xzvectors[i])){
 			/*At least one NaN found: default to Id*/
Index: sm/trunk/src/c/shared/Numerics/adolc_edf.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/adolc_edf.h	(revision 13974)
+++ 	(revision )
@@ -1,28 +1,0 @@
-/*
- * 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/cross.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/cross.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/cross.cpp	(revision 13975)
@@ -20,3 +20,2 @@
 
 }
-
Index: /issm/trunk/src/c/shared/Numerics/isnan.cpp
===================================================================
--- /issm/trunk/src/c/shared/Numerics/isnan.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/isnan.cpp	(revision 13975)
@@ -1,9 +1,15 @@
 /*This routine only used by Intel compler: */
+
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
 
 #include "../../include/include.h"
 #include "isnan.h"
 
-#ifdef _HAVE_ADOLC_
-template <> int xIsNan<adouble> (const adouble& X) {
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
+template <> int xIsNan<adouble> (const adouble& X){
   return isnan(X.getValue());
 }
Index: /issm/trunk/src/c/shared/Numerics/isnan.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/isnan.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/isnan.h	(revision 13975)
@@ -6,5 +6,12 @@
 #define _XISNAN_H_
 
-#include <cmath>
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*If include cmath instead of math, isnan on linux64 murdo does not work: */
+#include <math.h>
 
 template <class T> int xIsNan(const T& X) {
@@ -16,5 +23,5 @@
 }
 
-#ifdef _HAVE_ADOLC_
+#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
 template <> int xIsNan<adouble> (const adouble& X);
 #endif
Index: /issm/trunk/src/c/shared/Numerics/recast.h
===================================================================
--- /issm/trunk/src/c/shared/Numerics/recast.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Numerics/recast.h	(revision 13975)
@@ -9,5 +9,11 @@
 #define _RECAST_H_
 
-#ifndef _HAVE_ADOLC_
+#ifdef HAVE_CONFIG_H
+   #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#if !defined(_HAVE_ADOLC_) || defined(_WRAPPERS_)
 
 template<class To, class From>
Index: /issm/trunk/src/c/shared/Sorting/binary_search.cpp
===================================================================
--- /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Sorting/binary_search.cpp	(revision 13975)
@@ -11,5 +11,5 @@
 #include <stdio.h>
 
-int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){
+int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){ /*{{{*/
 
 	/*output: */
@@ -18,7 +18,7 @@
 
 	/*intermediary: */
-	int* beg=NULL;
-	int* end=NULL;
-	int* mid=NULL;
+	int *beg = NULL;
+	int *end = NULL;
+	int *mid = NULL;
 
 	// point to beginning and end of the array
@@ -47,5 +47,5 @@
 			}
 		}
-			  
+
 		//did we find the target?
 		if (*mid == target) {
@@ -60,6 +60,6 @@
 	/*Assign output pointers:*/
 	*poffset=offset;
-	
+
 	/*Return result: */
 	return found;
-}
+} /*}}}*/
Index: /issm/trunk/src/c/shared/Sorting/sorting.h
===================================================================
--- /issm/trunk/src/c/shared/Sorting/sorting.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Sorting/sorting.h	(revision 13975)
@@ -7,4 +7,55 @@
 
 int binary_search(int* poffset,int target,int* sorted_integers,int num_integers);
+template <typename doubletype> int binary_search(int* poffset,doubletype target,doubletype* list,int length){ /*{{{*/
+	/*
+	 *             l[0]  l[1]  l[2]        l[n]  l[n+1]   l[length-1]
+	 *     <-------+-----+-----+-----+ ... +-----+........+-------------->
+	 * offset: -1     0     1     2           n              length -1
+	 *  
+	 *  offset = -1        target < list[0]
+	 *  offset = n         list[n] <= target < list[n+1]
+	 *  offset = length-1  list[length-1] <= target
+	 */
+
+	/*output: */
+	int offset = 0;
+	int found  = 0;
+
+	/*intermediary: */
+	int n0 = 0;
+	int n1 = int(length/2);
+	int n2 = length-1;
+
+	if(target<list[n0]){
+		found  = 1;
+		offset = -1;
+	}
+	else if(target>=list[n2]){
+		found  = 1;
+		offset = length-1;
+	}
+	else{
+		for(;;){
+			/*did we find the target?*/
+			if(list[n1]<=target && list[n1+1]>target){
+				found  = 1;
+				offset = n1;
+				break;
+			}
+			else if(target < list[n1]){
+				n2 = n1;
+				n1 = n0 + int((n2-n0)/2);
+			}
+			else{
+				n0 = n1;
+				n1 = n0 + int((n2-n0)/2);
+			}
+		}
+	}
+
+	/*Assign output pointer and return*/
+	*poffset=offset;
+	return found;
+} /*}}}*/
 
 #endif //ifndef _SORTING_H_
Index: /issm/trunk/src/c/shared/String/DescriptorIndex.cpp
===================================================================
--- /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/String/DescriptorIndex.cpp	(revision 13975)
@@ -18,5 +18,5 @@
 
 int  DescriptorIndex(char* root, int* pindex,char* descriptor){ //We assume root has already been allocated, and we just have to copy into it.
-	
+
 	char * pch=NULL;
 
Index: /issm/trunk/src/c/shared/String/sharedstring.h
===================================================================
--- /issm/trunk/src/c/shared/String/sharedstring.h	(revision 13974)
+++ /issm/trunk/src/c/shared/String/sharedstring.h	(revision 13975)
@@ -8,4 +8,7 @@
 int  DescriptorIndex(char* root, int* pindex,char* descriptor);
 
+#ifndef WIN32
+int stricmp(const char* a,const char* b);
+#endif
+
 #endif //ifndef _SHAREDSTRING_H_
-
Index: /issm/trunk/src/c/shared/Threads/LaunchThread.cpp
===================================================================
--- /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Threads/LaunchThread.cpp	(revision 13975)
@@ -31,5 +31,5 @@
 	pthread_t      *threads = NULL;
 	pthread_handle *handles = NULL;
-	
+
 	/*dynamically allocate: */
 	threads=xNew<pthread_t>(num_threads);
@@ -52,5 +52,5 @@
 		}
 	}
-	
+
 	/*Free ressources:*/
 	xDelete<pthread_t>(threads);
@@ -62,5 +62,5 @@
 	handle.id=0;
 	handle.num=1;
-	
+
 	function((void*)&handle);
 	#endif
Index: /issm/trunk/src/c/shared/Threads/PartitionRange.cpp
===================================================================
--- /issm/trunk/src/c/shared/Threads/PartitionRange.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/Threads/PartitionRange.cpp	(revision 13975)
@@ -16,8 +16,7 @@
 	int i0=-1;
 	int i1=-1;
-	
+
 	int step;
 	int i;
-
 
 	/*distribute elements across threads :*/
@@ -29,5 +28,4 @@
 	}
 
-
 	/*Assign output pointers:*/
 	*pi0=i0;
Index: /issm/trunk/src/c/shared/Threads/issm_threads.h
===================================================================
--- /issm/trunk/src/c/shared/Threads/issm_threads.h	(revision 13974)
+++ /issm/trunk/src/c/shared/Threads/issm_threads.h	(revision 13975)
@@ -14,5 +14,4 @@
 } pthread_handle;
 
-
 /*routine that launches "function" in a multi-threaded way if requested, 
  * or just serially if not requested: */
Index: /issm/trunk/src/c/shared/TriMesh/AssociateSegmentToElement.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/TriMesh/AssociateSegmentToElement.cpp	(revision 13975)
@@ -6,5 +6,5 @@
 
 int AssociateSegmentToElement(double** psegments,int nseg, double* index,int nel){
-	
+
 	/*Error management: */
 	int i;
@@ -30,4 +30,2 @@
 	return noerr;
 }
-
-
Index: /issm/trunk/src/c/shared/TriMesh/OrderSegments.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/OrderSegments.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/TriMesh/OrderSegments.cpp	(revision 13975)
@@ -6,5 +6,5 @@
 
 int OrderSegments(double** psegments,int nseg, double* index,int nel){
-	
+
 	/*Error management: */
 	int i;
@@ -18,5 +18,4 @@
 	/*element indices: */
 	int el;
-
 
 	/*Recover segments: */
Index: /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp	(revision 13975)
@@ -12,8 +12,8 @@
 	x and y of size nodsx1
 	segments of size nsegsx3*/
-	
+
 	/*Error management: */
 	int noerr=1;
-	
+
 	int i,j,k,l;
 	int node;
@@ -23,5 +23,5 @@
 	int* riftsegments=NULL; 
 	int* flags=NULL;
-	
+
 	int  NumGridElementListOnOneSideOfRift;
 	int* GridElementListOnOneSideOfRift=NULL;
@@ -55,5 +55,5 @@
 	for (i=0;i<nriftsegs;i++){
 		for (j=0;j<2;j++){
-	
+
 			node=riftsegments[4*i+j+2];
 			if(flags[node-1]){
@@ -66,7 +66,7 @@
 
 			if(IsGridOnRift(riftsegments,nriftsegs,node)){
-			
+
 				DetermineGridElementListOnOneSideOfRift(&NumGridElementListOnOneSideOfRift,&GridElementListOnOneSideOfRift,i,nriftsegs,riftsegments,node,index,nel);
-			
+
 				/*Summary: we have for node, a list of elements
 				 * (GridElementListOnOneSideOfRift, of size
Index: /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 13974)
+++ /issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp	(revision 13975)
@@ -17,5 +17,5 @@
 	/*Does this node belong to 4 elements, or just 2? If it belongs to 4 elements, it is inside a rift, 
 	 *if it belongs to 2 elements, it is on the tip of a rift, or it has already been split across the rift (see below).*/
-	
+
 	int i;
 	int j;
@@ -119,8 +119,8 @@
 /*FUNCTION RiftSegmentsFromSegments{{{*/
 void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel, double* index, int nsegs,double* segments){
-	
+
 	int i,counter;
 	int el,el2;
-	
+
 	int  nriftsegs;
 	int* riftsegments=NULL;
@@ -179,5 +179,5 @@
 
 	xDelete<int>(riftsegments_uncompressed);
-	
+
 	/*Assign output pointers: */
 	*priftsegments=riftsegments;
@@ -266,5 +266,5 @@
 	/*Reallocate segments: */
 	segments         =xReNew<double>(segments,         nsegs*3,(nsegs+nriftsegs)*3);
-	segmentmarkerlist=xReNew<double>(segmentmarkerlist,nsegs*3,(nsegs+nriftsegs)*3);
+	segmentmarkerlist=xReNew<double>(segmentmarkerlist,nsegs,(nsegs+nriftsegs));
 
 	/*First, update the existing segments to the new nodes :*/
@@ -344,17 +344,6 @@
 	*psegmentmarkerlist=segmentmarkerlist;
 	*pnsegs=nsegs;
-	
+
 	return noerr;
-}/*}}}*/
-/*FUNCTION pnpoly{{{*/
-int pnpoly(int npol, double *xp, double *yp, double x, double y) {
-	int i, j, c = 0;
-	for (i = 0, j = npol-1; i < npol; j = i++) {
-		if ((((yp[i]<=y) && (y<yp[j])) ||
-					((yp[j]<=y) && (y<yp[i]))) &&
-				(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
-			c = !c;
-	}
-	return c;
 }/*}}}*/
 /*FUNCTION FindElement{{{*/
@@ -384,5 +373,5 @@
 	double *segmentmarkerlist = NULL;
 	int numsegs;
-	
+
 	/*output: */
 	int      new_numsegs;
@@ -460,5 +449,4 @@
 /*FUNCTION PairRiftElements{{{*/
 int PairRiftElements(int** priftsnumpairs, double*** priftspairs,int numrifts,int* riftsnumsegments, double** riftssegments,double* x,double* y){
-
 
 	int noerr=1;
@@ -693,5 +681,5 @@
 	int i;
 	int noerr=1;
-	
+
 	/*output: */
 	int riftflag=0;
@@ -717,5 +705,5 @@
 /*FUNCTION OrderRifts{{{*/
 int OrderRifts(double** priftstips, double** riftssegments,double** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels){
-	
+
 	int noerr=1;
 	int i,j,k,counter;
@@ -747,5 +735,5 @@
 		riftpairs=riftspairs[i];
 		numsegs=riftsnumsegments[i];
-	
+
 		/*Allocate copy of riftsegments and riftpairs, 
 		 *as well as ordering vector: */
@@ -793,5 +781,5 @@
 				}
 			}
-		
+
 			if (node4==node2){
 				/*node2 is a tip*/
@@ -818,5 +806,5 @@
 				node1=(int)*(riftsegments+3*j+0);
 				node2=(int)*(riftsegments+3*j+1);
-				
+
 				if ((node1==node) || (node2==node)){
 					/*Ok, this segment is connected to node, plug its index into order, unless we already plugged it before: */
@@ -851,5 +839,5 @@
 			*(riftpairs_copy+2*j+1)=*(riftpairs+2*order[j]+1);
 		}
-		
+
 		for (j=0;j<numsegs;j++){
 			*(riftsegments+3*j+0)=*(riftsegments_copy+3*j+0);
@@ -873,5 +861,4 @@
 int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,double** riftssegments,
 		int* riftsnumsegs,double** riftspairs,double* riftstips,double* x,double* y){
-		
 
 	int noerr=1;
@@ -906,5 +893,5 @@
 		/*allocate riftpenaltypairs, and riftnumpenaltypairs: */
 		if((numsegs/2-1)!=0)riftpenaltypairs=xNewZeroInit<double>((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH);
-		
+
 		/*Go through only one flank of the rifts, not counting the tips: */
 		counter=0;
@@ -997,5 +984,5 @@
 			*(riftpenaltypairs+j*7+5)=*(riftpenaltypairs+j*7+5)/magnitude;
 		}
-		
+
 		riftspenaltypairs[i]=riftpenaltypairs;
 		riftsnumpenaltypairs[i]=(numsegs/2-1);
@@ -1035,5 +1022,4 @@
 	y=*py;
 	nods=*pnods;
-
 
 	for (i=0;i<num_seg;i++){
Index: /issm/trunk/src/c/shared/TriMesh/trimesh.h
===================================================================
--- /issm/trunk/src/c/shared/TriMesh/trimesh.h	(revision 13974)
+++ /issm/trunk/src/c/shared/TriMesh/trimesh.h	(revision 13975)
@@ -22,5 +22,4 @@
 int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,double* index,int nel);
 int UpdateSegments(double** psegments,double** psegmentmarkerlist, int* pnsegs, double* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel);
-int pnpoly(int npol, double *xp, double *yp, double x, double y);
 int FindElement(double A,double B,double* index,int nel);
 int RemoveRifts(double** pindex,double** px,double** py,int* pnods,double** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,double** rifts1segments,double** rifts1pairs,int nel);
Index: /issm/trunk/src/c/shared/shared.h
===================================================================
--- /issm/trunk/src/c/shared/shared.h	(revision 13974)
+++ /issm/trunk/src/c/shared/shared.h	(revision 13975)
@@ -6,18 +6,17 @@
 #define _SHARED_H_
 
-#include "Alloc/alloc.h"
-#include "Alloc/xNewDelete.h"
-#include "Bamg/shared.h"
-#include "Elements/elements.h"
-#include "Exceptions/exceptions.h"
-#include "Exp/exp.h"
-#include "Matrix/matrix.h"
-#include "MemOps/xMemCpy.h"
-#include "Numerics/numerics.h"
-#include "Sorting/sorting.h"
-#include "Sys/sys.h"
-#include "Threads/issm_threads.h"
-#include "TriMesh/trimesh.h"
-#include "Wrapper/wrappershared.h"
+#include "./Alloc/alloc.h"
+#include "./Alloc/xNewDelete.h"
+#include "./Bamg/shared.h"
+#include "./Elements/elements.h"
+#include "./Exceptions/exceptions.h"
+#include "./Exp/exp.h"
+#include "./Matrix/matrix.h"
+#include "./MemOps/xMemCpy.h"
+#include "./Numerics/numerics.h"
+#include "./Sorting/sorting.h"
+#include "./String/sharedstring.h"
+#include "./Threads/issm_threads.h"
+#include "./TriMesh/trimesh.h"
 
 #endif
Index: /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp	(revision 13975)
@@ -1,3 +1,3 @@
-/*!\file:  CorePointerFromSolutionEnum.cpp
+/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
  * \brief: return type of analyses, number of analyses and core solution function.
  */ 
@@ -24,5 +24,5 @@
 
 	switch(solutiontype){
-	
+
 		case DiagnosticSolutionEnum:
 			adjointcore=&adjointdiagnostic_core;
@@ -38,5 +38,5 @@
 			break;
 	}
-	
+
 	/*Assign output pointer:*/
 	_assert_(padjointcore);
Index: /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp
===================================================================
--- /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/AnalysisConfiguration.cpp	(revision 13975)
@@ -26,5 +26,5 @@
 	/*Analyses lists*/
 	switch(solutiontype){
-	
+
 		case DiagnosticSolutionEnum:
 			numanalyses=5;
@@ -56,5 +56,5 @@
 			analyses[1]=MeltingAnalysisEnum;
 			break;
-		
+
 		case EnthalpySolutionEnum:
 			numanalyses=1;
@@ -62,5 +62,5 @@
 			analyses[0]=EnthalpyAnalysisEnum;
 			break;
-		
+
 		case HydrologySolutionEnum:
 			numanalyses=3;
@@ -108,5 +108,5 @@
 			analyses[8]=PrognosticAnalysisEnum;
 			break;
-		
+
 		default:
 			_error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
Index: /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp	(revision 13975)
@@ -24,5 +24,5 @@
 
 	switch(solutiontype){
-	
+
 		case DiagnosticSolutionEnum:
 			#ifdef _HAVE_DIAGNOSTIC_
@@ -99,5 +99,5 @@
 			break;
 	}
-	
+
 	/*Assign output pointer:*/
 	_assert_(psolutioncore);
Index: /issm/trunk/src/c/solutions/DakotaSpawnCore.cpp
===================================================================
--- /issm/trunk/src/c/solutions/DakotaSpawnCore.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/DakotaSpawnCore.cpp	(revision 13975)
@@ -0,0 +1,194 @@
+/*!\file:  DakotaSpawnCore.cpp
+
+ * \brief: run core ISSM solution using Dakota inputs coming from CPU 0.
+ * \sa qmu.cpp DakotaPlugin.cpp
+ *
+ * This routine needs to be understood simultaneously with qmu.cpp and DakotaPlugin. 
+ * DakotaSpawnCoreParallel is called by all CPUS, with CPU 0 holding Dakota variable values, along 
+ * with variable descriptors. 
+ *
+ * DakotaSpawnCoreParallel takes care of broadcasting the variables and their descriptors across the MPI 
+ * ring. Once this is done, we use the variables to modify the inputs for the solution core. 
+ * For ex, if "rho_ice" is provided, for ex 920, we include "rho_ice" in the inputs, then 
+ * call the core with the modified inputs. This is the way we get Dakota to explore the parameter 
+ * spce of the core. 
+ *
+ * Once the core is called, we process the results of the core, and using the processed results, 
+ * we compute response functions. The responses are computed on all CPUS, but they are targeted 
+ * for CPU 0, which will get these values back to the Dakota engine. 
+ *
+ */ 
+
+/*Includes and prototypes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../classes/objects/objects.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../solutions/solutions.h"
+#include "../modules/modules.h"
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses);
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses);
+
+/*}}}*/
+
+/*Notice the d_, which prefixes anything that is being provided to us by the Dakota pluggin. Careful. some things are ours, some are dakotas!: */
+int DakotaSpawnCore(double* d_responses, int d_numresponses, double* d_variables, char** d_variables_descriptors,int d_numvariables, void* void_femmodel,int counter){
+
+	char     **responses_descriptors    = NULL;      //these are our! there are only numresponsedescriptors of them, not d_numresponses!!!
+	int        numresponsedescriptors;
+	char      *string                   = NULL;
+	int        solution_type;
+	bool       control_analysis         = false;
+	void     (*solutioncore)(FemModel*) = NULL;
+	FemModel  *femmodel                 = NULL;
+	bool       nodakotacore             = true;
+
+	/*If counter==-1 on cpu0, it means that the dakota runs are done. In which case, bail out and return 0: */
+	#ifdef _HAVE_MPI_
+	MPI_Bcast(&counter,1,MPI_INT,0,IssmComm::GetComm()); 
+	#endif
+	if(counter==-1)return 0;
+
+	/*cast void_femmodel to FemModel: */
+	femmodel=reinterpret_cast<FemModel*>(void_femmodel);
+
+	/*retrieve parameters: */
+	femmodel->parameters->FindParam(&responses_descriptors,&numresponsedescriptors,QmuResponsedescriptorsEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+
+	if(VerboseQmu()) _pprintLine_("qmu iteration: " << counter);
+
+	/* only cpu 0, running dakota is providing us with variables and variables_descriptors and numresponses: broadcast onto other cpus: */
+	DakotaMPI_Bcast(&d_variables,&d_variables_descriptors,&d_numvariables,&d_numresponses);
+
+	/*Modify core inputs in objects contained in femmodel, to reflect the dakota variables inputs: */
+	InputUpdateFromDakotax(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,d_variables,d_variables_descriptors,d_numvariables);
+
+	/*Determine solution sequence: */
+	if(VerboseQmu()) _pprintLine_("Starting " << EnumToStringx(solution_type) << " core:");
+	WrapperCorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type,nodakotacore);
+
+	/*Run the core solution sequence: */
+	solutioncore(femmodel);
+
+	/*compute responses: */
+	if(VerboseQmu()) _pprintLine_("compute dakota responses:");
+	femmodel->DakotaResponsesx(d_responses,responses_descriptors,numresponsedescriptors,d_numresponses);
+
+	/*Free ressources:*/
+	DakotaFree(&d_variables,&d_variables_descriptors,&responses_descriptors, d_numvariables, numresponsedescriptors);
+
+	return 1; //this is critical! do not return 0, otherwise, dakota_core will stop running!
+}
+
+void DakotaMPI_Bcast(double** pvariables, char*** pvariables_descriptors,int* pnumvariables, int* pnumresponses){ /*{{{*/
+
+	/* * \brief: broadcast variables_descriptors, variables, numvariables and numresponses
+	 * from cpu 0 to all other cpus.
+	 */ 
+
+	int i;
+	int my_rank;
+
+	/*inputs and outputs: */
+	double* variables=NULL;
+	char**  variables_descriptors=NULL;
+	int     numvariables;
+	int     numresponses;
+
+	/*intermediary: */
+	char* string=NULL;
+	int   string_length;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*recover inputs from pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	numvariables=*pnumvariables;
+	numresponses=*pnumresponses;
+
+	/*numvariables: */
+	MPI_Bcast(&numvariables,1,MPI_INT,0,IssmComm::GetComm()); 
+
+	/*variables:*/
+	if(my_rank!=0)variables=xNew<double>(numvariables);
+	MPI_Bcast(variables,numvariables,MPI_DOUBLE,0,IssmComm::GetComm()); 
+
+	/*variables_descriptors: */
+	if(my_rank!=0){
+		variables_descriptors=xNew<char*>(numvariables);
+	}
+	for(i=0;i<numvariables;i++){
+		if(my_rank==0){
+			string=variables_descriptors[i];
+			string_length=(strlen(string)+1)*sizeof(char);
+		}
+		MPI_Bcast(&string_length,1,MPI_INT,0,IssmComm::GetComm()); 
+		if(my_rank!=0)string=xNew<char>(string_length);
+		MPI_Bcast(string,string_length,MPI_CHAR,0,IssmComm::GetComm()); 
+		if(my_rank!=0)variables_descriptors[i]=string;
+	}
+
+	/*numresponses: */
+	MPI_Bcast(&numresponses,1,MPI_INT,0,IssmComm::GetComm()); 
+
+	/*Assign output pointers:*/
+	*pnumvariables=numvariables;
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*pnumresponses=numresponses;
+} /*}}}*/
+void DakotaFree(double** pvariables,char*** pvariables_descriptors,char*** presponses_descriptors,int numvariables,int numresponses){ /*{{{*/
+
+	/*\brief DakotaFree: free allocations on other cpus, not done by Dakota.*/
+
+	int i;
+	int my_rank;
+
+	double  *variables             = NULL;
+	char   **variables_descriptors = NULL;
+	char   **responses_descriptors = NULL;
+	char    *string                = NULL;
+
+	/*recover pointers: */
+	variables=*pvariables;
+	variables_descriptors=*pvariables_descriptors;
+	responses_descriptors=*presponses_descriptors;
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	/*Free variables and variables_descriptors only on cpu !=0*/
+	if(my_rank!=0){
+		xDelete<double>(variables);
+		for(i=0;i<numvariables;i++){
+			string=variables_descriptors[i];
+			xDelete<char>(string);
+		}
+		xDelete<char*>(variables_descriptors);
+	}
+
+	//responses descriptors on every cpu
+	for(i=0;i<numresponses;i++){
+		string=responses_descriptors[i];
+		xDelete<char>(string);
+	}
+	//rest of dynamic allocations.
+	xDelete<char*>(responses_descriptors);
+
+	/*Assign output pointers:*/
+	*pvariables=variables;
+	*pvariables_descriptors=variables_descriptors;
+	*presponses_descriptors=responses_descriptors;
+} /*}}}*/
Index: /issm/trunk/src/c/solutions/EnvironmentFinalize.cpp
===================================================================
--- /issm/trunk/src/c/solutions/EnvironmentFinalize.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/EnvironmentFinalize.cpp	(revision 13975)
@@ -0,0 +1,29 @@
+/*!\file:  EnvironmentFinalize.cpp
+ * \brief: finalize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "../include/include.h"
+#include "../toolkits/toolkits.h"
+#include "../shared/shared.h"
+
+void EnvironmentFinalize(void){
+
+	#ifdef _HAVE_MPI_
+
+	/*Make sure we are all here*/
+	MPI_Barrier(MPI_COMM_WORLD);
+	
+	/*Print closing statement*/
+	int my_rank;
+	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
+	if(!my_rank) printf("closing MPI\n");
+
+	/*Finalize: */
+	MPI_Finalize();
+
+	#endif
+}
Index: /issm/trunk/src/c/solutions/EnvironmentInit.cpp
===================================================================
--- /issm/trunk/src/c/solutions/EnvironmentInit.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/EnvironmentInit.cpp	(revision 13975)
@@ -0,0 +1,38 @@
+/*!\file:  EnvironmentInit.cpp
+ * \brief: initialize Petsc, MPI, you name it
+ */ 
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include "../include/include.h"
+#include "../toolkits/toolkits.h"
+
+COMM EnvironmentInit(int argc,char** argv){
+
+	/*Output*/
+	COMM comm = 0;
+
+	/*Initialize MPI environment: */
+	#if defined(_HAVE_MPI_)
+	MPI_Init(&argc,&argv);
+	comm = MPI_COMM_WORLD;
+	#else
+	comm = 1; //bogus number for comm, which does not exist anyway.
+	#endif
+
+	/*Print Banner*/
+	int my_rank = 0;
+	#ifdef _HAVE_MPI_
+	MPI_Comm_rank(comm,&my_rank);
+	#endif
+	if(!my_rank) printf("\n");
+	if(!my_rank) printf("Ice Sheet System Model (%s) version  %s\n",PACKAGE_NAME,PACKAGE_VERSION);
+	if(!my_rank) printf("(website: %s contact: %s\n",PACKAGE_URL,PACKAGE_BUGREPORT);
+	if(!my_rank) printf("\n");
+
+	/*Return communicator*/
+	return comm;
+}
Index: /issm/trunk/src/c/solutions/ProcessArguments.cpp
===================================================================
--- /issm/trunk/src/c/solutions/ProcessArguments.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/ProcessArguments.cpp	(revision 13975)
@@ -19,8 +19,11 @@
 	char *rootpatharg    = NULL;
 
-	*solution_type=StringToEnumx(argv[1]);
+	/*Check input arguments*/
 	if(argc<2)_error_("Usage error: no solution requested");
 	if(argc<3)_error_("Usage error: missing execution directory");
 	if(argc<4)_error_("Usage error: missing model name");
+
+	/*Get requested solution*/
+	*solution_type=StringToEnumx(argv[1]);
 
 	rootpatharg=argv[2];
Index: /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp
===================================================================
--- /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp	(revision 13975)
@@ -9,12 +9,11 @@
 
 void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
-	
+
 	/*variables: */
 	Vector<IssmDouble>*    yg    = NULL;
 	Nodes *nodes = NULL;
-	int    i;
 
 	if(VerboseSolution()) _pprintLine_("   updating boundary conditions...");
-			
+
 	/*set current analysis: */
 	femmodel->SetCurrentConfiguration(analysis_type);
Index: /issm/trunk/src/c/solutions/WrapperCorePointerFromSolutionEnum.cpp
===================================================================
--- /issm/trunk/src/c/solutions/WrapperCorePointerFromSolutionEnum.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/WrapperCorePointerFromSolutionEnum.cpp	(revision 13975)
@@ -0,0 +1,60 @@
+/*!\file:  WrapperCorePointerFromSolutionEnum.cpp
+ * \brief: return type of analyses, number of analyses and core solution function.
+ */ 
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "../toolkits/toolkits.h"
+#include "../classes/objects/objects.h"
+#include "../shared/shared.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore){
+
+	/*output: */
+	void (*solutioncore)(FemModel*)=NULL;
+
+	/*parameters: */
+	bool control_analysis=false;
+	bool tao_analysis=false;
+	bool dakota_analysis=false;
+
+	/* retrieve some parameters that tell us whether wrappers are allowed, or whether we return 
+	 * a pure core. Wrappers can be dakota_core (which samples many solution_cores) or control_core (which 
+	 * carries out adjoint based inversion on a certain core: */
+	parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
+	parameters->FindParam(&control_analysis,InversionIscontrolEnum);
+	parameters->FindParam(&tao_analysis,InversionTaoEnum);
+
+	if(nodakotacore)dakota_analysis=false;
+
+	if(dakota_analysis){
+		#ifdef _HAVE_DAKOTA_
+		solutioncore=dakota_core;
+		#else
+		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
+		#endif
+	}
+	else if(control_analysis){
+		#ifdef _HAVE_CONTROL_
+		if(tao_analysis) solutioncore=controltao_core;
+		else solutioncore=control_core;
+		#else
+		_error_("ISSM was not compiled with control support, cannot carry out control analysis!");
+		#endif
+	}
+	else CorePointerFromSolutionEnum(&solutioncore,parameters,solutiontype);  /*This means we retrieve a core solution that is not a wrapper*/
+
+	/*Assign output pointer:*/
+	_assert_(psolutioncore);
+	*psolutioncore=solutioncore;
+
+}
Index: sm/trunk/src/c/solutions/WriteLockFile.cpp
===================================================================
--- /issm/trunk/src/c/solutions/WriteLockFile.cpp	(revision 13974)
+++ 	(revision )
@@ -1,25 +1,0 @@
-/*!\file:  WriteLockFile.cpp
- * \brief
- */ 
-#include <stdio.h>
-#include "../shared/shared.h"
-#include "../include/include.h"
-
-void WriteLockFile(char* filename){
-
-	int i;
-	extern int my_rank;
-	
-	/* output: */
-	FILE* fid=NULL;
-
-	/* Open lock file and write 1 into it: */
-	if(my_rank==0){
-		fid=fopen(filename,"w");
-		if(fid==NULL) _error_("error message: could not open lock file " << filename);
-
-		/*Close file: */
-		if(fclose(fid)!=0) _error_("could not close lock file " << filename);
-	}
-
-}	
Index: /issm/trunk/src/c/solutions/ad_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/ad_core.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/ad_core.cpp	(revision 13975)
@@ -0,0 +1,308 @@
+/*!\file ad_core
+ * \brief: compute outputs from the AD mode,  using our dependents and independents, and drivers available in Adolc.
+ */
+
+/*Includes: {{{*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <set>
+#include "../toolkits/toolkits.h"
+#include "../classes/objects/objects.h"
+#include "../shared/shared.h"
+#include "../io/io.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "./solutions.h"
+#include "../modules/modules.h"
+#include "../include/include.h"
+#include "../solvers/solvers.h"
+/*}}}*/
+
+void ad_core(FemModel* femmodel){
+
+	/*diverse: */
+	int     i;
+	int     dummy;
+	int     num_dependents;
+	int     num_independents;
+	bool    isautodiff       = false;
+	char   *driver           = NULL;
+	size_t  tape_stats[11];
+
+	/*state variables: */
+	IssmDouble *axp = NULL;
+	double     *xp  = NULL;
+
+	/*AD mode on?: */
+	femmodel->parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
+
+	if(isautodiff){
+
+		#ifdef _HAVE_ADOLC_
+
+			/*First, stop tracing: */
+			trace_off();
+
+			/*preliminary checks: */
+			femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
+			femmodel->parameters->FindParam(&num_independents,AutodiffNumIndependentsEnum);
+			if(!(num_dependents*num_independents)) return;
+
+			if(VerboseAutodiff())_pprintLine_("   start ad core");
+
+			/*retrieve state variable: */
+			femmodel->parameters->FindParam(&axp,&dummy,AutodiffXpEnum);
+
+			/* driver argument */
+			xp=xNew<double>(num_independents);
+			for(i=0;i<num_independents;i++){
+				xp[i]=reCast<double,IssmDouble>(axp[i]);
+			}
+
+			/*get the EDF pointer:*/
+			ext_diff_fct *anEDF_for_solverx_p=dynamic_cast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
+
+			/*Branch according to AD driver: */
+			femmodel->parameters->FindParam(&driver,AutodiffDriverEnum);
+
+			/* these are always needed regardless of the interpreter */
+			anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
+			anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+			if (strcmp(driver,"fos_forward")==0){
+
+				int     anIndepIndex;
+				double *tangentDir         = NULL;
+				double *jacTimesTangentDir = NULL;
+				double *theOutput          = NULL;
+
+				/*retrieve direction index: */
+				femmodel->parameters->FindParam(&anIndepIndex,AutodiffFosForwardIndexEnum);
+
+				if (anIndepIndex<0 || anIndepIndex>=num_independents) _error_("index value for AutodiffFosForwardIndexEnum should be in [0,num_independents-1]");
+
+				tangentDir=xNewZeroInit<double>(num_independents);
+				tangentDir[anIndepIndex]=1.0;
+
+				jacTimesTangentDir=xNew<double>(num_dependents);
+				theOutput=xNew<double>(num_dependents);
+
+				/*set the forward method function pointer: */
+				anEDF_for_solverx_p->fos_forward=EDF_fos_forward_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_forward:*/
+				anEDF_for_solverx_p->dp_X=xNew<double>(anEDF_for_solverx_p->max_n);
+				anEDF_for_solverx_p->dp_Y=xNew<double>(anEDF_for_solverx_p->max_m);
+
+				/*call driver: */
+				fos_forward(1,num_dependents,num_independents, 0, xp, tangentDir, theOutput, jacTimesTangentDir );
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,jacTimesTangentDir,num_dependents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(theOutput);
+				xDelete(jacTimesTangentDir);
+				xDelete(tangentDir);
+			}
+			else if ((strcmp(driver,"fov_forward")==0) || (strcmp(driver,"fov_forward_all")==0)){
+
+				int      tangentDirNum;
+				int      dummy;
+				int     *indepIndices  = NULL;
+				double **jacTimesSeed  = NULL;
+				double **seed          = NULL;
+				double  *theOutput     = NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_forward_all")==0){
+					tangentDirNum=num_independents;
+					indepIndices=xNewZeroInit<int>(tangentDirNum);
+					for(i=0;i<num_independents;i++)indepIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&indepIndices,&tangentDirNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (tangentDirNum<1 || tangentDirNum>num_independents) _error_("tangentDirNum should be in [1,num_independents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				jacTimesSeed=xNew<double>(num_dependents,tangentDirNum);
+
+				/*set the forward method function pointers: */
+				anEDF_for_solverx_p->fov_forward=EDF_fov_forward_for_solverx;
+				// anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke EDF fov_forward:*/
+				anEDF_for_solverx_p->dpp_X=xNew<double>(anEDF_for_solverx_p->max_n, tangentDirNum);
+				anEDF_for_solverx_p->dpp_Y=xNew<double>(anEDF_for_solverx_p->max_m, tangentDirNum);
+
+				/*seed matrix: */
+				seed=xNewZeroInit<double>(num_independents,tangentDirNum);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<tangentDirNum; ++i) {
+					/* make sure the index is in range*/
+					if (indepIndices[i]>num_independents) {
+						_error_("indepIndices values must be in [0,num_independents-1]");
+					}
+					if (anIndexSet.find(indepIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate indepIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(indepIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					seed[indepIndices[i]][i]=1.0;
+				}
+
+				/*allocate output: */
+				theOutput=xNew<double>(num_dependents);
+
+				/*call driver: */
+				fov_forward(1,num_dependents,num_independents, tangentDirNum, xp, seed, theOutput, jacTimesSeed );
+				/*Free resources: */
+				xDelete(theOutput);
+				xDelete(indepIndices);
+				xDelete(seed);
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*jacTimesSeed,num_dependents*tangentDirNum,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(jacTimesSeed);
+				xDelete(indepIndices);
+			}
+			else if (strcmp(driver,"fos_reverse")==0) {
+
+				int     aDepIndex=0;
+				double *aWeightVector=NULL;
+				double *weightVectorTimesJac=NULL;
+
+				/*retrieve direction index: */
+				femmodel->parameters->FindParam(&aDepIndex,AutodiffFosReverseIndexEnum);
+
+				if (aDepIndex<0 || aDepIndex>=num_dependents) _error_("index value for AutodiffFosReverseIndexEnum should be in [0,num_dependents-1]");
+
+				aWeightVector=xNewZeroInit<double>(num_dependents);
+				aWeightVector[aDepIndex]=1.0;
+
+				weightVectorTimesJac=xNew<double>(num_independents);
+
+				/*set the forward method function pointer: */
+				anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dp_U=xNew<double>(anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dp_Z=xNew<double>(anEDF_for_solverx_p->max_n);
+
+				/*call driver: */
+				fos_reverse(1,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
+
+				/*add to results*/
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,weightVectorTimesJac,num_independents,1,1,0.0));
+
+				/*free resources :*/
+				xDelete(weightVectorTimesJac);
+				xDelete(aWeightVector);
+			}
+			else if ((strcmp(driver,"fov_reverse")==0) || (strcmp(driver,"fov_reverse_all")==0)){
+
+				int* depIndices=NULL;
+				int weightNum;
+				int dummy;
+				double **weightsTimesJac=NULL;
+				double **weights=NULL;
+				std::set<unsigned int> anIndexSet;
+
+				/*retrieve directions:*/
+				if (strcmp(driver,"fov_reverse_all")==0){
+					weightNum=num_dependents;
+					depIndices=xNewZeroInit<int>(weightNum);
+					for(i=0;i<num_dependents;i++)depIndices[i]=1;
+				}
+				else{
+					femmodel->parameters->FindParam(&depIndices,&weightNum,&dummy,AutodiffFovForwardIndicesEnum);
+				}
+
+				/*Some checks: */
+				if (weightNum<1 || weightNum>num_dependents) _error_("tangentDirNum should be in [1,num_dependents]");
+
+				/* full Jacobian or Jacobian projection:*/
+				weightsTimesJac=xNew<double>(weightNum,num_independents);
+
+				/*set the forward method function pointers: */
+				anEDF_for_solverx_p->fov_reverse=EDF_fov_reverse_for_solverx;
+
+				/*allocate the space for the parameters to invoke the EDF fos_reverse :*/
+				anEDF_for_solverx_p->dpp_U=xNew<double>(weightNum,anEDF_for_solverx_p->max_m);
+				anEDF_for_solverx_p->dpp_Z=xNew<double>(weightNum,anEDF_for_solverx_p->max_n);
+
+				/*seed matrix: */
+				weights=xNewZeroInit<double>(weightNum,num_dependents);
+
+				/*collect indices in a set to prevent accidental duplicates as long as we don't do compression:*/
+				for (int i=0; i<weightNum; ++i) {
+					/* make sure the index is in range*/
+					if (depIndices[i]>num_dependents) {
+						_error_("depIndices values must be in [0,num_dependents-1]");
+					}
+					if (anIndexSet.find(depIndices[i])!=anIndexSet.end()) {
+						_error_("duplicate depIndices values are not allowed until we implement Jacobian decompression");
+					}
+					anIndexSet.insert(depIndices[i]);
+					/* now populate the seed matrix from the set of independent indices;
+					 * simple setup with a single 1.0 per column and at most a single 1.0 per row*/
+					weights[depIndices[i]][i]=1.0;
+				}
+
+				/*call driver: */
+				fov_reverse(1,num_dependents,num_independents, weightNum, weights, weightsTimesJac );
+
+				/*add to results: */
+				femmodel->results->AddObject(new GenericExternalResult<IssmPDouble*>(femmodel->results->Size()+1,AutodiffJacobianEnum,*weightsTimesJac,weightNum*num_independents,1,1,0.0));
+
+				/*Free resources: */
+				xDelete(weights);
+				xDelete(weightsTimesJac);
+				xDelete(depIndices);
+			}
+			else _error_("driver: " << driver << " not yet supported!");
+
+			/* delete the allocated space for the parameters:*/
+			xDelete(anEDF_for_solverx_p->dp_x);
+			xDelete(anEDF_for_solverx_p->dp_X);
+			xDelete(anEDF_for_solverx_p->dpp_X);
+			xDelete(anEDF_for_solverx_p->dp_y);
+			xDelete(anEDF_for_solverx_p->dp_Y);
+			xDelete(anEDF_for_solverx_p->dpp_Y);
+			xDelete(anEDF_for_solverx_p->dp_U);
+			xDelete(anEDF_for_solverx_p->dpp_U);
+			xDelete(anEDF_for_solverx_p->dp_Z);
+			xDelete(anEDF_for_solverx_p->dpp_Z);
+
+			/*Print statistics:*/
+			tapestats(1,tape_stats); //reading of tape statistics
+			if(VerboseAutodiff()){
+				_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]);
+			}
+			if(VerboseAutodiff())_pprintLine_("   end AD core");
+
+			/*Free resources: */
+			xDelete(xp);
+			xDelete(axp); 
+		#else
+			_error_("Should not be requesting AD drivers when an AD library is not available!");
+		#endif
+	}
+}
Index: /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp	(revision 13975)
@@ -14,5 +14,5 @@
 
 void adjointbalancethickness_core(FemModel* femmodel){
-	
+
 	/*parameters: */
 	bool save_results;
@@ -33,5 +33,5 @@
 	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
 	solver_adjoint_linear(femmodel);
-	
+
 	/*Save results*/
 	if(save_results){
Index: /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp	(revision 13975)
@@ -14,5 +14,5 @@
 
 void adjointdiagnostic_core(FemModel* femmodel){
-	
+
 	/*parameters: */
 	bool isstokes;
@@ -36,5 +36,5 @@
 	femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
 	solver_adjoint_linear(femmodel);
-	
+
 	/*Save results*/
 	if(save_results){
Index: /issm/trunk/src/c/solutions/balancethickness_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/balancethickness_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/balancethickness_core.cpp	(revision 13975)
@@ -20,5 +20,5 @@
 	/*activate formulation: */
 	femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
-	
+
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
Index: /issm/trunk/src/c/solutions/bedslope_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/bedslope_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/bedslope_core.cpp	(revision 13975)
@@ -26,5 +26,5 @@
 	femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
 	solver_linear(femmodel);
-	
+
 	if(save_results){
 		if(VerboseSolution()) _pprintLine_("   saving results");
Index: /issm/trunk/src/c/solutions/control_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/control_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/control_core.cpp	(revision 13975)
@@ -16,5 +16,5 @@
 
 	int     i,n;
-	
+
 	/*parameters: */
 	int     num_controls,num_responses;
@@ -32,5 +32,5 @@
 	IssmDouble* maxiter=NULL;
 	IssmDouble* cm_jump=NULL;
-		
+
 	/*intermediary: */
 	IssmDouble  search_scalar=1;
@@ -72,9 +72,9 @@
 	J=xNew<IssmDouble>(nsteps);
 	step_responses=xNew<int>(num_responses);
-		
+
 	/*Initialize some of the BrentSearch arguments: */
 	optargs.femmodel=femmodel;
 	optpars.xmin=0; optpars.xmax=1;
-	
+
 	/*Start looping: */
 	for(n=0;n<nsteps;n++){
@@ -84,5 +84,5 @@
 		for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
 		femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
-		
+
 		/*In steady state inversion, compute new temperature field now*/
 		if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
@@ -104,5 +104,5 @@
 		if(VerboseControl()) _pprintLine_("   updating parameter using optimized search scalar"); //true means update save controls
 		InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
-		
+
 		if(controlconvergence(J[n],tol_cm)) break;
 	}
Index: /issm/trunk/src/c/solutions/controlconvergence.cpp
===================================================================
--- /issm/trunk/src/c/solutions/controlconvergence.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/controlconvergence.cpp	(revision 13975)
@@ -19,5 +19,4 @@
 bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
 
-	int i;
 	bool converged=false;
 
Index: /issm/trunk/src/c/solutions/controltao_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/controltao_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/controltao_core.cpp	(revision 13975)
@@ -54,5 +54,5 @@
 
 	/*Initialize TAO*/
-	TaoCreate(PETSC_COMM_WORLD,&tao);
+	TaoCreate(IssmComm::GetComm(),&tao);
 	if(VerboseControl()) _pprintLine_("   Initializing the Toolkit for Advanced Optimization (TAO)");
 	TaoSetFromOptions(tao);
@@ -99,4 +99,5 @@
 	/*Clean up and return*/
 	xDelete<int>(control_list);
+	xDelete<double>(user.J);
 	xdelete(&X);
 	TaoDestroy(&tao);
@@ -141,5 +142,5 @@
 
 	/*Compute objective function*/
-	CostFunctionx(fcn,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	femmodel->CostFunctionx(fcn);
 
 	/*Compute gradient*/
@@ -173,5 +174,5 @@
 	/*Retrieve objective functions independently*/
 	for(i=0;i<num_responses;i++){
-		Responsex(&f,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnumToStringx(responses[i]),false,i);
+		femmodel->Responsex(&f,EnumToStringx(responses[i]),false,i);
 		_pprintString_(" "<<setw(12)<<setprecision(7)<<f);
 	}
Index: /issm/trunk/src/c/solutions/dakota_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/dakota_core.cpp	(revision 13975)
+++ /issm/trunk/src/c/solutions/dakota_core.cpp	(revision 13975)
@@ -0,0 +1,127 @@
+/*!\file:  dakota_core.cpp
+ * \brief: wrapper to the Dakota capabilities. qmu fires up Dakota, and registers a Dakota Pluggin
+ * which will be in charge of running the solution sequences repeteadly, to garner statistics. 
+ *
+ * This routine deals with running ISSM and Dakota in library mode. In library mode, Dakota does not 
+ * run as an execuatble. Its capabilities are linked into the ISSM software. ISSM calls dakota routines 
+ * directly from the dakota library. qmu.cpp is the code that is in charge of calling those routines. 
+ *
+ * Dakota has its own way of running in parallel (for embarassingly parallel jobs). We do not want that, 
+ * as ISSM knows exactly how to run "really parallel" jobs that use all CPUS. To bypass Dakota's parallelism, 
+ * we overloaded the constructor for the parallel library (see the Dakota patch in the externalpackages/dakota
+ * directory). This overloaded constructor fires up Dakota serially on CPU 0 only! We take care of broadcasting 
+ * to the other CPUS, hence ISSM is running in parallel, and Dakota serially on CPU0. 
+ *
+ * Now, how does CPU 0 drive all other CPUS to carry out sensitivity analysese? By synchronizing its call to 
+ * our ISSM cores (diagnostic_core, thermal_core, transient_core, etc ...) on CPU 0 with all other CPUS. 
+ * This explains the structure of qmu.cpp, where cpu 0 runs Dakota, the Dakota pluggin fires up DakotaSpawnCore.cpp, 
+ * while the other CPUS are waiting for a broadcast from CPU0, once they get it, they also fire up 
+ * DakotaSpawnCore. In the end, DakotaSpawnCore is fired up on all CPUS, with CPU0 having Dakota inputs, that it will 
+ * broacast to other CPUS. 
+ *
+ * Now, how does dakota call the DakotaSpawnCore routine? The DakotaSpawnCore is embedded into the DakotaPlugin object 
+ * which is derived from the Direct Interface Dakota objct. This is the only way to run Dakota in library 
+ * mode (see their developper guide for more info). Dakota registers the DakotaPlugin object into its own 
+ * database, and calls on the embedded DakotaSpawnCore from CPU0. 
+ *
+ */ 
+
+/*include files: {{{*/
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./solutions.h"
+#include "../shared/shared.h"
+#include "../include/include.h"
+#include "../io/io.h"
+#include "../toolkits/toolkits.h"
+#include "../EnumDefinitions/EnumDefinitions.h"
+#include "../classes/dakota/DakotaPlugin.h"
+
+#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+#include <ParallelLibrary.H>
+#include <ProblemDescDB.H>
+#include <DakotaStrategy.H>
+#include <DakotaModel.H>
+#include <DakotaInterface.H>
+#endif
+/*}}}*/
+
+void dakota_core(FemModel* femmodel){ 
+
+	#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
+
+	int                my_rank;
+	char*              dakota_input_file  = NULL;
+	char*              dakota_output_file = NULL;
+	char*              dakota_error_file  = NULL;
+	int                status=0;
+	Dakota::ModelLIter ml_iter;
+	Parameters* parameters                = NULL;
+
+	/*Recover dakota_input_file, dakota_output_file and dakota_error_file, in the parameters dataset in parallel */
+	femmodel->parameters->FindParam(&dakota_input_file,QmuInNameEnum);
+	femmodel->parameters->FindParam(&dakota_output_file,QmuOutNameEnum);
+	femmodel->parameters->FindParam(&dakota_error_file,QmuErrNameEnum);
+
+	/*recover my_rank:*/
+	my_rank=IssmComm::GetRank();
+
+	if(my_rank==0){
+
+		// Instantiate/initialize the parallel library and problem description
+		// database objects.
+		Dakota::ParallelLibrary parallel_lib("serial"); //use our own ISSM Dakota library mode constructor, which only fires up Dakota on CPU 0. 
+		Dakota::ProblemDescDB problem_db(parallel_lib); 
+
+		// Manage input file parsing, output redirection, and restart processing
+		// without a CommandLineHandler.  This version relies on parsing of an
+		// input file.
+		problem_db.manage_inputs(dakota_input_file);
+		// specify_outputs_restart() is only necessary if specifying non-defaults
+		parallel_lib.specify_outputs_restart(dakota_output_file,dakota_error_file,NULL,NULL);
+
+		// Instantiate the Strategy object (which instantiates all Model and
+		// Iterator objects) using the parsed information in problem_db.
+		Dakota::Strategy selected_strategy(problem_db);
+
+		// convenience function for iterating over models and performing any
+		// interface plug-ins
+		Dakota::ModelList& models = problem_db.model_list();
+
+		for (ml_iter = models.begin(); ml_iter != models.end(); ml_iter++) {
+
+			Dakota::Interface& interface = ml_iter->interface();
+
+			//set DB nodes to the existing Model specification
+			problem_db.set_db_model_nodes(ml_iter->model_id());
+
+			// Serial case: plug in derived Interface object without an analysisComm
+			interface.assign_rep(new SIM::DakotaPlugin(problem_db,(void*)femmodel), false);
+		}
+
+		// Execute the strategy
+		problem_db.lock(); // prevent run-time DB queries
+		selected_strategy.run_strategy();
+
+		//Warn other cpus that we are done running the dakota iterator, by setting the counter to -1:
+		DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,-1);
+
+	}
+	else{
+
+		for(;;){
+			if(!DakotaSpawnCore(NULL,0, NULL,NULL,0,femmodel,0))break; //counter came in at -1 on cpu0, bail out.
+		}
+	}
+
+	/*Free ressources:*/
+	xDelete<char>(dakota_input_file);
+	xDelete<char>(dakota_error_file);
+	xDelete<char>(dakota_output_file);
+
+	#endif //#ifdef _HAVE_DAKOTA_
+}
Index: /issm/trunk/src/c/solutions/diagnostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/diagnostic_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/diagnostic_core.cpp	(revision 13975)
@@ -60,5 +60,5 @@
 
 	if(ishutter){
-			
+
 		if(VerboseSolution()) _pprintLine_("   computing hutter velocities");
 
@@ -68,10 +68,10 @@
 		femmodel->SetCurrentConfiguration(DiagnosticHutterAnalysisEnum);
 		solver_linear(femmodel);
-		
+
 		if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHorizAnalysisEnum);
 	}
 
 	if ((ismacayealpattyn || isl1l2) ^ isstokes){ // ^ = xor
-		
+
 		if(VerboseSolution()) _pprintLine_("   computing velocities");
 		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
@@ -95,5 +95,4 @@
 	}
 
-
 	if(save_results){
 		if(VerboseSolution()) _pprintLine_("   saving results");
@@ -103,6 +102,8 @@
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
 		if(dim==3) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
-		RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
 	}
+
+	if(solution_type==DiagnosticSolutionEnum)femmodel->RequestedDependentsx();
 
 	/*Free ressources:*/
Index: /issm/trunk/src/c/solutions/hydrology_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/hydrology_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/hydrology_core.cpp	(revision 13975)
@@ -44,5 +44,5 @@
 	/*Loop through time: */
 	for(i=0;i<nsteps;i++){
-		
+
 		if(nsteps)if(VerboseSolution()) _pprintLine_("time step:" << i+1 << "/" << nsteps);
 		time+=dt;
@@ -57,5 +57,5 @@
 			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum,i+1,time);
 			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVyEnum,i+1,time);
-			
+
 			/*unload results*/
 			if(VerboseSolution()) _pprintLine_("   saving temporary results");
@@ -64,3 +64,2 @@
 	}
 }
-
Index: /issm/trunk/src/c/solutions/hydrology_core_step.cpp
===================================================================
--- /issm/trunk/src/c/solutions/hydrology_core_step.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/hydrology_core_step.cpp	(revision 13975)
@@ -14,5 +14,5 @@
 
 void hydrology_core_step(FemModel* femmodel,int step, IssmDouble time){
-	
+
 	bool modify_loads=true;
 
Index: /issm/trunk/src/c/solutions/issm.cpp
===================================================================
--- /issm/trunk/src/c/solutions/issm.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/issm.cpp	(revision 13975)
@@ -1,252 +1,35 @@
 /*!\file:  issm.cpp
- * \brief: ISSM main parallel program
+ * \brief: ISSM main program
  */ 
 
 #include "../issm.h"
-#include "../include/globals.h"
-#include "../shared/Numerics/adolc_edf.h"
 
 int main(int argc,char **argv){
 
-	/*I/O: */
-	FILE *output_fid       = NULL;
-	FILE *petscoptionsfid  = NULL;
-	bool  waitonlock       = false;
-	bool  dakota_analysis,control_analysis,tao_analysis;
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
 
-	/*AD: */
-	bool autodiff=false;
-	size_t   tape_stats[11];
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	COMM comm_init=EnvironmentInit(argc,argv);
 
-	/*FemModel: */
-	FemModel *femmodel = NULL;
+	/*Initialize femmodel from arguments provided command line: */
+	FemModel *femmodel = new FemModel(argc,argv,comm_init);
 
-	/*configuration: */
-	void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
-	int* analyses=NULL;
-	int  numanalyses;
-	int  solution_type;
+	/*Solve: */
+	femmodel->Solve();
 
-	/*File names*/
-	char *lockfilename   = NULL;
-	char *binfilename    = NULL;
-	char *outbinfilename = NULL;
-	char *petscfilename  = NULL;
-	char *rootpath       = NULL;
+	/*Output results: */
+	femmodel->OutputResults();
 
-	/*time*/
-	IssmPDouble   start, finish;
-	IssmPDouble   start_core, finish_core;
-	IssmPDouble   start_init, finish_init;
-	int      ierr;
-
-	/*profiling*/   
-	bool profiling = false;
-	IssmPDouble Time_start, Flops_start;
-	IssmPDouble Solution_time, Memory_use, Current_flops;
-
-	ISSMBOOT();
-
-	
-	/*Initialize environments: Petsc, MPI, etc...: */
-	#ifdef _HAVE_PETSC_
-	ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error_("Could not initialize Petsc");
-	#else
-	#ifdef _HAVE_MPI_
-	MPI_Init(&argc,&argv);
-	#endif
-	#endif
-
-	#ifdef _HAVE_MPI_
-	MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
-	#else
-	start=(IssmPDouble)clock();
-	#endif
-
-	/*Size and rank: */
-	#ifdef _HAVE_MPI_
-	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);  
-	MPI_Comm_size(MPI_COMM_WORLD,&num_procs); 
-	#endif
-
-	/*First process inputs*/
-	_pprintLine_("");
-	_pprintLine_("Ice Sheet System Model (" << PACKAGE_NAME << ") version " << PACKAGE_VERSION);
-	_pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
-	_pprintLine_("");
-	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_
-	MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
-	#else
-	start_init=(IssmPDouble)clock();
-	#endif
-	femmodel=new FemModel(rootpath,binfilename,outbinfilename,solution_type,analyses,numanalyses);
-	
-	/*get type of solution we are going to run: */
-	CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
-
-	/*Open output file once for all*/
-	output_fid=pfopen(outbinfilename,"wb");
-	femmodel->parameters->SetParam(output_fid,OutputFilePointerEnum);
-
-	/*add petsc options to parameters: */
-	petscoptionsfid=pfopen(petscfilename,"r");
-	ParsePetscOptionsx(femmodel->parameters,petscoptionsfid);
-	pfclose(petscoptionsfid,petscfilename);
-
-	/*get parameters: */
-	femmodel->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
-	femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
-	femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
-	femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
-	femmodel->parameters->FindParam(&profiling,DebugProfilingEnum); 
-	femmodel->parameters->FindParam(&autodiff,AutodiffIsautodiffEnum);
-
-	#ifdef _HAVE_MPI_
-	MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
-	#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
-
-	_pprintLine_("call computational core:");
-	#ifdef _HAVE_MPI_
-	MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
-	#else
-	start_core=(IssmPDouble)clock();
-	#endif
-	
-	if(profiling)ProfilingStart(&Time_start,&Flops_start);
-
-	if(dakota_analysis){
-		#ifdef _HAVE_DAKOTA_
-		Dakotax(femmodel);
-		#else
-		_error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
-		#endif
-	}
-	else if(control_analysis){
-		#ifdef _HAVE_CONTROL_
-		if(tao_analysis)
-		 controltao_core(femmodel);
-		else
-		 control_core(femmodel);
-		#else
-		_error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
-		#endif
-	}
-	else{
-		solutioncore(femmodel);
-	}
-
-	if(profiling){
-		ProfilingEnd(&Solution_time,&Memory_use,&Current_flops,Time_start,Flops_start);
-		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
-
-
-	#ifdef _HAVE_MPI_
-	MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
-	#else
-	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*/
-	pfclose(output_fid,lockfilename);
-	if (waitonlock>0){
-		_pprintLine_("write lock file:");
-		WriteLockFile(lockfilename);
-	}
-
-	/*Free resources */
-	xDelete<int>(analyses);
-	xDelete<char>(lockfilename);
-	xDelete<char>(binfilename);
-	xDelete<char>(outbinfilename);
-	xDelete<char>(petscfilename);
-	xDelete<char>(rootpath);
+	/*Wrap up: */
 	delete femmodel;
 
-	/*Get finish time and close*/
-	#ifdef _HAVE_MPI_
-	MPI_Barrier(MPI_COMM_WORLD); finish = MPI_Wtime( );
-	_pprintLine_("");
-	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<finish_init-start_init);
-	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<finish_core-start_core);
-	_pprintLine_("");
-	_pprintLine_("   Total elapsed time:"<<int((finish-start)/3600)<<" hrs "<<int(int(finish-start)%3600/60)<<" min "<<int(finish-start)%60<<" sec");
-	_pprintLine_("");
-	#else
-	finish=(IssmPDouble)clock();
-	_pprintLine_("");
-	_pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<(finish_init-start_init)/CLOCKS_PER_SEC);
-	_pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<(finish_core-start_core)/CLOCKS_PER_SEC);
-	_pprintLine_("");
-	_pprintLine_("   Total elapsed time:"
-				<<int((finish-start)/CLOCKS_PER_SEC/3600)<<" hrs "
-				<<int(int(finish-start)/CLOCKS_PER_SEC%3600/60)<<" min "
-				<<int(finish-start)/CLOCKS_PER_SEC%60<<" sec");
-	_pprintLine_("");
-	#endif
-	
-	#ifdef _HAVE_PETSC_
-	_pprintLine_("closing MPI and Petsc");
-	PetscFinalize(); 
-	#else
-	#ifdef _HAVE_MPI_
-	_pprintLine_("closing MPI and Petsc");
-	MPI_Finalize();
-	#endif
-	#endif
+	/*Finalize environment:*/
+	EnvironmentFinalize();
 
-	
-	/*end module: */
-	ISSMEND();
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
 
-	return 0; //unix success return;
+	/*Return unix success: */
+	return 0; 
 }
Index: /issm/trunk/src/c/solutions/kriging.cpp
===================================================================
--- /issm/trunk/src/c/solutions/kriging.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/kriging.cpp	(revision 13975)
@@ -4,9 +4,11 @@
 
 #include "../issm.h"
-#include "../include/globals.h"
 
 /*Local prototypes*/
 void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv);
 void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid);
+
+int my_rank;
+int num_procs;
 
 int main(int argc,char **argv){
@@ -23,4 +25,8 @@
 	char *rootpath       = NULL;
 
+	MPI_Comm comm;
+	extern int my_rank;
+	extern int num_procs;
+
 	/*Input*/
 	int         ninterp,nobs;
@@ -36,21 +42,12 @@
 	IssmDouble *error       = NULL;
 
-	ISSMBOOT();
+	/*Initialize exception trapping: */
+	ExceptionTrapBegin();
 
-	/*Initialize environments: Petsc, MPI, etc...: */
-#ifdef _HAVE_PETSC_
-	int ierr=PetscInitialize(&argc,&argv,(char*)0,"");  
-	if(ierr) _error_("Could not initialize Petsc");
-#else
-#ifdef _HAVE_MPI_
-	MPI_Init(&argc,&argv);
-#endif
-#endif
+	/*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
+	comm=EnvironmentInit(argc,argv);
 
-	/*Size and rank: */
-#ifdef _HAVE_MPI_
-	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);  
-	MPI_Comm_size(MPI_COMM_WORLD,&num_procs); 
-#endif
+	MPI_Comm_size(comm,&num_procs);
+	MPI_Comm_rank(comm,&my_rank);
 
 	/*First process inputs*/
@@ -76,5 +73,5 @@
 		results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
 		for(int i=0;i<results->Size();i++){
-			ExternalResult* result=(ExternalResult*)results->GetObjectByOffset(i);
+			ExternalResult* result=dynamic_cast<ExternalResult*>(results->GetObjectByOffset(i));
 			result->WriteData(output_fid,1);
 		}
@@ -101,16 +98,9 @@
 	delete results;
 
-#ifdef _HAVE_PETSC_
-	_pprintLine_("closing MPI and Petsc");
-	PetscFinalize(); 
-#else
-#ifdef _HAVE_MPI_
-	_pprintLine_("closing MPI and Petsc");
-	MPI_Finalize();
-#endif
-#endif
+	/*Finalize environment:*/
+	EnvironmentFinalize();
 
-	/*end module: */
-	ISSMEND();
+	/*Finalize exception trapping: */
+	ExceptionTrapEnd();
 
 	return 0; //unix success return;
@@ -166,5 +156,5 @@
 	Option  *option   = NULL;
 
-	int dummy,M,N;
+	int      M,N;
 	IoModel* iomodel = new IoModel();
 	iomodel->fid=fid;
Index: /issm/trunk/src/c/solutions/objectivefunction.cpp
===================================================================
--- /issm/trunk/src/c/solutions/objectivefunction.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/objectivefunction.cpp	(revision 13975)
@@ -22,9 +22,7 @@
 IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
 
-	int i;  
-	
 	/*output: */
 	IssmDouble J;
-	
+
 	/*parameters: */
 	int        solution_type,analysis_type;
@@ -70,5 +68,5 @@
 
 	/*Compute misfit for this velocity field.*/
-	CostFunctionx(&J, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
+	femmodel->CostFunctionx(&J);
 
 	/*Free ressources:*/
Index: /issm/trunk/src/c/solutions/prognostic_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/prognostic_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/prognostic_core.cpp	(revision 13975)
@@ -17,8 +17,11 @@
 	bool save_results;
 	bool issmbgradients,ispdd,isdelta18o;
+	int  solution_type;
+	int  *requested_outputs = NULL;
+	int  numoutputs=0;
 
 	/*activate formulation: */
 	femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
-	
+
 	/*recover parameters: */
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
@@ -26,4 +29,7 @@
 	femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
 	femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
+	femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
+	femmodel->parameters->FindParam(&numoutputs,PrognosticNumRequestedOutputsEnum);
+	if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,PrognosticRequestedOutputsEnum);
 
 	if(issmbgradients){
@@ -41,8 +47,14 @@
 	if(VerboseSolution()) _pprintLine_("   call computational core");
 	solver_linear(femmodel);
-	
+
 	if(save_results){
 		if(VerboseSolution()) _pprintLine_("   saving results");
 		InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
 	}
+
+	if(solution_type==PrognosticSolutionEnum)femmodel->RequestedDependentsx();
+
+	/*Free ressources:*/
+	xDelete<int>(requested_outputs);
 }
Index: /issm/trunk/src/c/solutions/solutions.h
===================================================================
--- /issm/trunk/src/c/solutions/solutions.h	(revision 13974)
+++ /issm/trunk/src/c/solutions/solutions.h	(revision 13975)
@@ -8,4 +8,5 @@
 #include "../classes/objects/objects.h"
 #include "../io/io.h"
+#include "../toolkits/toolkits.h"
 
 struct OptArgs;
@@ -30,4 +31,6 @@
 void steadystate_core(FemModel* femmodel);
 void transient_core(FemModel* femmodel);
+void dakota_core(FemModel* femmodel);
+void ad_core(FemModel* femmodel);
 IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
 
@@ -45,8 +48,13 @@
 void controlrestart(FemModel* femmodel,IssmDouble* J);
 void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
+COMM EnvironmentInit(int argc,char** argv);
+void EnvironmentFinalize(void);
+int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
+void PrintBanner(void);
 
 //solution configuration
 void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype);
 void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
+void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
 void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
 
Index: /issm/trunk/src/c/solutions/steadystate_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/steadystate_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/steadystate_core.cpp	(revision 13975)
@@ -29,5 +29,5 @@
 	int  numoutputs         = 0;
 	int  *requested_outputs = NULL;
-	
+
 	/* recover parameters:*/
 	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
@@ -42,5 +42,5 @@
 
 	for(;;){
-	
+
 		if(VerboseSolution()) _pprintLine_("   computing temperature and velocity for step: " << step);
 		#ifdef _HAVE_THERMAL_
@@ -66,5 +66,5 @@
 			break;
 		}
-		
+
 		if(VerboseSolution()) _pprintLine_("   saving velocity, temperature and pressure to check for convergence at next step");
 		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum,VxPicardEnum);
@@ -73,9 +73,9 @@
 		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum,PressurePicardEnum);
 		InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,TemperatureOldEnum);
-		
+
 		//increase counter
 		step++;
 	}
-	
+
 	if(save_results){
 		if(VerboseSolution()) _pprintLine_("   saving results");
@@ -89,5 +89,5 @@
 		if(isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum);
 		if(!isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
-		RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
+		femmodel->RequestedOutputsx(requested_outputs,numoutputs);
 	}
 
Index: /issm/trunk/src/c/solutions/steadystateconvergence.cpp
===================================================================
--- /issm/trunk/src/c/solutions/steadystateconvergence.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/steadystateconvergence.cpp	(revision 13975)
@@ -18,5 +18,5 @@
 
 bool steadystateconvergence(FemModel* femmodel){
-	
+
 	/*output: */
 	bool converged=false;
@@ -32,5 +32,5 @@
 	/*retrieve parameters: */
 	femmodel->parameters->FindParam(&convergencecriterionvalue[0],SteadystateReltolEnum);
-	
+
 	/*figure out convergence at the input level, because we don't have the solution vectors!: */
 	velocity_converged=InputConvergencex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,&velocityenums[0],8,&convergencecriterion[0],&convergencecriterionvalue[0],1);
Index: /issm/trunk/src/c/solutions/surfaceslope_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/surfaceslope_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/surfaceslope_core.cpp	(revision 13975)
@@ -26,5 +26,5 @@
 	femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
 	solver_linear(femmodel);
-	
+
 	if(save_results){
 		if(VerboseSolution()) _pprintLine_("saving results:");
Index: /issm/trunk/src/c/solutions/thermal_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/thermal_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/thermal_core.cpp	(revision 13975)
@@ -16,5 +16,4 @@
 
 	/*intermediary*/
-	IssmDouble melting_offset;
 	bool   save_results;
 	bool   dakota_analysis  = false;
Index: /issm/trunk/src/c/solutions/transient_core.cpp
===================================================================
--- /issm/trunk/src/c/solutions/transient_core.cpp	(revision 13974)
+++ /issm/trunk/src/c/solutions/transient_core.cpp	(revision 13975)
@@ -31,5 +31,5 @@
 	int    numoutputs         = 0;
 	int    *requested_outputs = NULL;
-	
+
 	/*intermediary: */
 	int    step;
@@ -78,5 +78,5 @@
 		/*Increment*/
 		if(time_adapt){
-			TimeAdaptx(&dt,femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters); 
+			femmodel->TimeAdaptx(&dt);
 			if(time+dt>finaltime) dt=finaltime-time;
 			femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
@@ -107,5 +107,5 @@
 			#endif
 		}
-		
+
 		if(isdiagnostic){
 			if(VerboseSolution()) _pprintLine_("   computing new velocity");
@@ -121,5 +121,5 @@
 			prognostic_core(femmodel);
 			if(VerboseSolution()) _pprintLine_("   updating vertices positions");
-			UpdateVertexPositionsx(femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters); 
+			femmodel->UpdateVertexPositionsx();
 		}
 
@@ -140,5 +140,5 @@
 			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMassBalanceEnum);
 			InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,MaskElementonfloatingiceEnum);
-			RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
+			femmodel->RequestedOutputsx(requested_outputs,numoutputs);
 
 			if(isdelta18o){
@@ -152,6 +152,6 @@
 	}
 
-	RequestedDependentsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
-	
+	femmodel->RequestedDependentsx();
+
 	/*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 13974)
+++ /issm/trunk/src/c/solvers/solver_adjoint_linear.cpp	(revision 13975)
@@ -24,7 +24,7 @@
 	/*Recover parameters: */
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	femmodel->UpdateConstraintsx();
 
-	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys,true); xdelete(&Kfs); //true means spc = 0
Index: /issm/trunk/src/c/solvers/solver_linear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_linear.cpp	(revision 13974)
+++ /issm/trunk/src/c/solvers/solver_linear.cpp	(revision 13975)
@@ -22,7 +22,7 @@
 	/*Recover parameters: */
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	femmodel->UpdateConstraintsx();
 
-	SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+	femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
 	CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 	Reduceloadx(pf, Kfs, ys); xdelete(&Kfs);
Index: /issm/trunk/src/c/solvers/solver_newton.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_newton.cpp	(revision 13974)
+++ /issm/trunk/src/c/solvers/solver_newton.cpp	(revision 13975)
@@ -15,5 +15,4 @@
 	/*intermediary: */
 	bool   converged;
-	int    num_unstable_constraints;
 	int    count;
 	IssmDouble kmax;
@@ -38,5 +37,5 @@
 	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	femmodel->UpdateConstraintsx();
 
 	count=1;
@@ -57,5 +56,5 @@
 
 		/*Solver forward model*/
-		SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf,Kfs,ys);xdelete(&Kfs);
@@ -84,5 +83,5 @@
 
 		/*Prepare next iteration using Newton's method*/
-		SystemMatricesx(&Kff,&Kfs,&pf,NULL,&kmax,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf,Kfs,ys);   xdelete(&Kfs);
@@ -91,5 +90,5 @@
 		pJf->Scale(-1.0); pJf->AXPY(pf,+1.0);     xdelete(&pf);
 
-		CreateJacobianMatrixx(&Jff,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,kmax);
+		femmodel->CreateJacobianMatrixx(&Jff,kmax);
 		Solverx(&duf,Jff,pJf,NULL,NULL,femmodel->parameters); xdelete(&Jff); xdelete(&pJf);
 		uf->AXPY(duf, 1.0); xdelete(&duf);
Index: /issm/trunk/src/c/solvers/solver_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_nonlinear.cpp	(revision 13974)
+++ /issm/trunk/src/c/solvers/solver_nonlinear.cpp	(revision 13975)
@@ -23,6 +23,6 @@
 	Vector<IssmDouble>* df  = NULL;
 	Vector<IssmDouble>* ys  = NULL;
-	
-	Loads* loads=NULL;
+
+	Loads* savedloads=NULL;
 	bool converged;
 	int constraints_converged;
@@ -33,5 +33,5 @@
 	int min_mechanical_constraints;
 	int max_nonlinear_iterations;
-	int  configuration_type;
+	int configuration_type;
 
 	/*Recover parameters: */
@@ -39,9 +39,10 @@
 	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
 	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	femmodel->UpdateConstraintsx();
 
 	/*Were loads requested as output? : */
-	if(conserve_loads) loads=(Loads*)femmodel->loads->Copy(); //protect loads from being modified by the solution
-	else               loads=(Loads*)femmodel->loads;         //modify loads  in this solution
+	if(conserve_loads){
+		savedloads = static_cast<Loads*>(femmodel->loads->Copy());
+	}
 
 	count=1;
@@ -49,5 +50,5 @@
 
 	/*Start non-linear iteration using input velocity: */
-	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices, loads, femmodel->materials, femmodel->parameters);
+	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
 	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
 
@@ -62,5 +63,5 @@
 		xdelete(&old_uf);old_uf=uf;
 
-		SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); xdelete(&Kfs);
@@ -72,5 +73,5 @@
 		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
 
-		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
+		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
 		if(VerboseConvergence()) _pprintLine_("   number of unstable constraints: " << num_unstable_constraints);
 
@@ -108,5 +109,8 @@
 
 	/*clean-up*/
-	if(conserve_loads) delete loads;
+	if(conserve_loads){
+		delete femmodel->loads;
+		femmodel->loads=savedloads;
+	}
 	xdelete(&uf);
 	xdelete(&ug);
Index: /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 13974)
+++ /issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp	(revision 13975)
@@ -14,21 +14,19 @@
 
 	/*intermediary: */
-	Matrix<IssmDouble>*  Kff_horiz = NULL;
-	Matrix<IssmDouble>* Kfs_horiz   = NULL;
-	Vector<IssmDouble>*  ug_horiz  = NULL;
-	Vector<IssmDouble>*  uf_horiz  = NULL;
-	Vector<IssmDouble>*  old_uf_horiz = NULL;
-	Vector<IssmDouble>*  pf_horiz  = NULL;
-	Vector<IssmDouble>*  df_horiz  = NULL;
-	Matrix<IssmDouble>*  Kff_vert  = NULL;
-	Matrix<IssmDouble>*  Kfs_vert  = NULL;
-	Vector<IssmDouble>*  ug_vert   = NULL;
-	Vector<IssmDouble>*  uf_vert   = NULL;
-	Vector<IssmDouble>*  pf_vert   = NULL;
-	Vector<IssmDouble>*  df_vert   = NULL;
-	Vector<IssmDouble>*  ys   = NULL;
+	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;
-	int  num_unstable_constraints;
 	int  count;
 
@@ -41,6 +39,6 @@
 	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
 	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
-	
+	femmodel->UpdateConstraintsx();
+
 	count=1;
 	converged=false;
@@ -56,5 +54,5 @@
 		femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
 		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-	
+
 		//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
 		InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
@@ -65,5 +63,5 @@
 
 		/*solve: */
-		SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_horiz, Kfs_horiz, ys); xdelete(&Kfs_horiz);
@@ -77,7 +75,7 @@
 		femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
 		femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
-		
+
 		/*solve: */
-		SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf_vert, Kfs_vert, ys); xdelete(&Kfs_vert);
Index: /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp
===================================================================
--- /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 13974)
+++ /issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp	(revision 13975)
@@ -36,5 +36,4 @@
 	int  configuration_type;
 
-
 	/*Recover parameters: */
 	kflag=1; pflag=1;
@@ -50,9 +49,9 @@
 	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
 	InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
-	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
+	femmodel->UpdateConstraintsx();
 
 	for(;;){
 
-		SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
+		femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset);
 		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
 		Reduceloadx(pf, Kfs, ys); xdelete(&Kfs); xdelete(&tf);
@@ -76,5 +75,5 @@
 
 		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
-		
+
 		if(converged)break;
 	}
Index: /issm/trunk/src/c/toolkits/issm/SeqMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqMat.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/issm/SeqMat.h	(revision 13975)
@@ -30,5 +30,5 @@
 
 	public:
-	
+
 		int M,N; 
 		doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
@@ -61,8 +61,15 @@
 		}
 		/*}}}*/
+		/*FUNCTION SeqMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+		SeqMat(int m,int n,int pM,int pN,int* d_nnz,int* o_nnz){
+
+			this->M=pM;
+			this->N=pN;
+			this->matrix=NULL;
+			if(pM*pN) this->matrix=xNewZeroInit<doubletype>(pM*pN);
+		}
+		/*}}}*/
 		/*FUNCTION SeqMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
 		SeqMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
-
-			int i,j;
 
 			this->M=pM;
Index: /issm/trunk/src/c/toolkits/issm/SeqVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/issm/SeqVec.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/issm/SeqVec.h	(revision 13975)
@@ -29,5 +29,5 @@
 
 	public:
-	
+
 		doubletype* vector;
 		int M;
@@ -49,4 +49,12 @@
 		}
 		/*}}}*/
+		/*FUNCTION SeqVec(int m,int M){{{*/
+		SeqVec(int pm,int pM){
+
+			this->M=pM;
+			this->vector=NULL;
+			if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
+		}
+		/*}}}*/
 		/*FUNCTION SeqVec(int M,bool fromlocalsize){{{*/
 		SeqVec(int pM,bool fromlocalsize){
@@ -59,6 +67,4 @@
 		/*FUNCTION SeqVec(doubletype* serial_vec,int M){{{*/
 		SeqVec(doubletype* buffer,int pM){
-
-			int i,j;
 
 			this->M=pM;
Index: /issm/trunk/src/c/toolkits/mpi/mpiincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/mpiincludes.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/mpi/mpiincludes.h	(revision 13975)
@@ -7,5 +7,5 @@
 
 /*MPI includes: */
-#include "mpi.h"
+#include <mpi.h>
 
 /*Patches: */
Index: /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp	(revision 13975)
@@ -6,6 +6,7 @@
 #include <math.h>
 #include "../../../shared/shared.h"
+#include "../../../include/types.h"
 
-int DetermineLocalSize(int global_size){
+int DetermineLocalSize(int global_size,COMM comm){
 
 	/*output: */
@@ -18,7 +19,11 @@
 
 	/*from MPI: */
-	extern int num_procs;
-	extern int my_rank;
-	
+	int num_procs;
+	int my_rank;
+
+	/*recover my_rank*/
+	MPI_Comm_rank(comm,&my_rank);
+	MPI_Comm_size(comm,&num_procs);
+
 	/*We are  not bound by any library, just use what seems most logical*/
 	num_local_rows=xNew<int>(num_procs);    
@@ -30,5 +35,5 @@
 		num_local_rows[i]=(int)floor((double)global_size/(double)num_procs); 
 	}
-	
+
 	/*There may be some rows left. Distribute evenly.*/ 
 	row_rest=global_size - num_procs*(int)floor((double)global_size/(double)num_procs);
@@ -37,5 +42,5 @@
 	}
 	local_size=num_local_rows[my_rank];
-	
+
 	/*free ressources: */
 	xDelete<int>(num_local_rows);
Index: sm/trunk/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/MPI_Boundariesfromrange.cpp	(revision 13974)
+++ 	(revision )
@@ -1,38 +1,0 @@
-/*!\file MPI_Boundariesfromrange.cpp
- * \brief: routine to figure out from a range distribution, the lower and upper 
- * bounds for the current cpu.
- */
-
-#include "./mpipatches.h"
-#include "../../../shared/shared.h"
-
-int MPI_Boundariesfromrange(int* plower_row, int* pupper_row,int range){
-
-	extern int num_procs;
-	extern int my_rank;
-	
-	/*output: */
-	int lower_row,upper_row;
-
-	/*intermediary: */
-	int  i;
-	int* allranges=NULL;
-
-	/*Gather all range values into allranges, for all nodes*/
-	allranges=xNew<int>(num_procs);
-	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
-
-	/*From all ranges, get lower row and upper row*/
-	lower_row=0;
-	upper_row=lower_row+allranges[0];
-	for (i=1;i<=my_rank;i++){
-		lower_row=lower_row+allranges[i-1];
-		upper_row=upper_row+allranges[i];
-	}
-
-	/*Assign output pointers: */
-	xDelete<int>(allranges);
-	*plower_row=lower_row;
-	*pupper_row=upper_row;
-	return 1;
-}
Index: sm/trunk/src/c/toolkits/mpi/patches/MPI_Lowerrow.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/MPI_Lowerrow.cpp	(revision 13974)
+++ 	(revision )
@@ -1,27 +1,0 @@
-/*!\file MPI_Lowerrow.cpp
- * \brief: routine to distribute jobs in parallel. 
- * This handy routine will provide, along with the MPI_Upperrow, a distributed range 
- * for an index (like i,j, in a for loop). 
- * Ex: for(i=MPI_Lowerrow(num_procs)0;i<MPI_Upperrow(num_procs);i++)
- * This ensures easy parallelisation of loops if needed.
- */
-
-#include "./mpipatches.h"
-
-int MPI_Lowerrow(int n){
-
-
-	int range;
-	int lower_row;
-	int upper_row;
-	
-
-	/*First, figure out our range : */
-	range=DetermineLocalSize(n);
-
-	/*Now determien upper and lower boundaries: */
-	MPI_Boundariesfromrange(&lower_row,&upper_row,range);
-
-	return lower_row;
-	
-}
Index: sm/trunk/src/c/toolkits/mpi/patches/MPI_Upperrow.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/MPI_Upperrow.cpp	(revision 13974)
+++ 	(revision )
@@ -1,30 +1,0 @@
-/*!\file MPI_Upperrow.cpp
- * \brief: routine to distribute jobs in parallel. 
- * This handy routine will provide, along with the MPI_Lowrrow, a distributed range 
- * for an index (like i,j, in a for loop). 
- * Ex: for(i=MPI_Lowerrow(num_procs)0;i<MPI_Upperrow(num_procs);i++)
- * This ensures easy parallelisation of loops if needed.
- */
-
-#include "./mpipatches.h"
-
-int MPI_Upperrow(int n){
-
-	int range;
-	int lower_row;
-	int upper_row;
-
-	/*First, figure out our range : */
-	range=DetermineLocalSize(n);
-
-	/*Now determien upper and lower boundaries: */
-	MPI_Boundariesfromrange(&lower_row,&upper_row,range);
-
-	return upper_row;
-	
-}
-
-
-
-
-
Index: /issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h	(revision 13975)
@@ -3,16 +3,10 @@
  */
 
-
 #ifndef MPI_PATCHES_H_ 
 #define MPI_PATCHES_H_
 
+#include "../../../include/types.h"
 
-int MPI_Boundariesfromrange(int* plower_row, int* pupper_row,int range);
-int MPI_Lowerrow(int n);
-int MPI_Upperrow(int n);
-int DetermineLocalSize(int global_size);
-
-
-
+int DetermineLocalSize(int global_size,COMM comm);
 
 #endif
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp	(revision 13975)
@@ -31,5 +31,5 @@
 PetscMat::PetscMat(int M,int N){
 
-	this->matrix=NewMat(M,N);
+	this->matrix=NewMat(M,N,IssmComm::GetComm());
 }
 /*}}}*/
@@ -37,8 +37,19 @@
 PetscMat::PetscMat(int M,int N, IssmDouble sparsity){
 
-	this->matrix=NewMat(M,N,sparsity);
+	this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
 }
 /*}}}*/
-/*FUNCTION PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
+/*FUNCTION PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
+PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){
+
+	MatCreate(IssmComm::GetComm(),&this->matrix);
+	MatSetSizes(this->matrix,m,n,M,N);
+	MatSetFromOptions(this->matrix);
+	MatMPIAIJSetPreallocation(this->matrix,0,d_nnz,0,o_nnz);
+	//MatSetOption(this->matrix,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
+
+}
+/*}}}*/
+/*FUNCTION PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
 PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){
 
@@ -46,5 +57,5 @@
 	int* idxm=NULL;
 	int* idxn=NULL;
-	
+
 	if(M)idxm=xNew<int>(M);
 	if(N)idxn=xNew<int>(N);
@@ -53,6 +64,5 @@
 	for(i=0;i<N;i++)idxn[i]=i;
 
-
-	this->matrix=NewMat(M,N,sparsity);
+	this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
 	MatSetValues(this->matrix,M,idxm,N,idxn,serial_mat,INSERT_VALUES);
 	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
@@ -66,6 +76,6 @@
 /*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);
+
+	this->matrix=NewMat(M,N,connectivity,numberofdofspernode,IssmComm::GetComm());
 
 }
@@ -78,4 +88,18 @@
 
 /*PetscMat specific routines: */
+/*FUNCTION PetscMat::AllocationInfo{{{*/
+void PetscMat::AllocationInfo(void){
+
+	MatInfo info;
+	MatGetInfo(this->matrix,MAT_GLOBAL_SUM,&info);
+	_pprintLine_("=========================== Stiffness matrix allocation info ===========================");
+	_pprintLine_("");
+	_pprintLine_(" nz_allocated: "<<info.nz_allocated);
+	_pprintLine_(" nz_used     : "<<info.nz_used);
+	_pprintLine_(" nz_unneeded : "<<info.nz_unneeded<<" ("<<double(info.nz_unneeded)/double(info.nz_allocated)*100.<<"%)");
+	_pprintLine_("");
+	_pprintLine_("========================================================================================");
+}
+/*}}}*/
 /*FUNCTION PetscMat::Echo{{{*/
 void PetscMat::Echo(void){
@@ -90,7 +114,4 @@
 	MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
 	MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
-	#if _PETSC_MAJOR_ == 2 
-		MatCompress(this->matrix);
-	#endif
 
 }
@@ -99,9 +120,8 @@
 IssmDouble PetscMat::Norm(NormMode mode){
 
-
 	IssmDouble norm=0;
 	_assert_(this->matrix);
 	MatNorm(this->matrix,ISSMToPetscNormMode(mode),&norm);
-	
+
 	return norm;
 
@@ -128,5 +148,5 @@
 	_assert_(this->matrix);
 	_assert_(X->vector);
-	MatMultPatch(this->matrix,X->vector,AX->vector);
+	MatMultPatch(this->matrix,X->vector,AX->vector,IssmComm::GetComm());
 
 }
@@ -135,7 +155,5 @@
 PetscMat* PetscMat::Duplicate(void){
 
-	PetscMat* output=NULL;
-
-	output=new PetscMat();
+	PetscMat* output=new PetscMat();
 	_assert_(this->matrix);
 	MatDuplicate(this->matrix,MAT_COPY_VALUES,&output->matrix);
@@ -150,5 +168,5 @@
 	 IssmDouble* output=NULL;
 
-	 MatToSerial(&output,this->matrix);
+	 MatToSerial(&output,this->matrix,IssmComm::GetComm());
 	 return output;
 
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h	(revision 13975)
@@ -31,13 +31,15 @@
 		#endif
 
-		/*PetscMat constructors, destructors {{{*/
+		/*PetscMat constructors, destructors*/
 		PetscMat();
 		PetscMat(int M,int N);
 		PetscMat(int M,int N,IssmDouble sparsity);
+		PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz);
 		PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity);
 		PetscMat(int M,int N,int connectivity,int numberofdofspernode);
 		~PetscMat();
-		/*}}}*/
-		/*PetscMat specific routines {{{*/
+
+		/*PetscMat specific routines*/
+		void AllocationInfo(void);
 		void Echo(void);
 		void Assemble(void);
@@ -50,7 +52,5 @@
 		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 13974)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp	(revision 13975)
@@ -29,6 +29,16 @@
 /*FUNCTION PetscVec::PetscVec(int M,bool fromlocalsize){{{*/
 PetscVec::PetscVec(int M,bool fromlocalsize){
-	
-	this->vector=NewVec(M,fromlocalsize);
+
+	this->vector=NewVec(M,IssmComm::GetComm(),fromlocalsize);
+
+}
+/*}}}*/
+/*FUNCTION PetscVec::PetscVec(int m,int M){{{*/
+PetscVec::PetscVec(int m,int M){
+
+	VecCreate(IssmComm::GetComm(),&this->vector);
+	VecSetSizes(this->vector,m,M);
+	VecSetFromOptions(this->vector);
+	VecSet(this->vector,0.0);
 
 }
@@ -38,5 +48,5 @@
 
 	if(petsc_vec==NULL){
-		this->vector=NewVec(0);
+		this->vector=NewVec(0,IssmComm::GetComm());
 	}
 	else{
@@ -55,5 +65,5 @@
 	for(int i=0;i<M;i++) idxm[i]=i;
 
-	this->vector=NewVec(M);
+	this->vector=NewVec(M,IssmComm::GetComm());
 	VecSetValues(this->vector,M,idxm,serial_vec,INSERT_VALUES);
 	VecAssemblyBegin(this->vector);
@@ -79,5 +89,5 @@
 /*FUNCTION PetscVec::Assemble{{{*/
 void PetscVec::Assemble(void){
-		
+
 	_assert_(this->vector);
 	VecAssemblyBegin(this->vector); 
@@ -88,5 +98,5 @@
 /*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));
@@ -128,10 +138,9 @@
 /*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);
+	PetscVec* output=new PetscVec(vec_output);
 	VecFree(&vec_output);
 
@@ -165,7 +174,7 @@
 /*FUNCTION PetscVec::ToMPISerial{{{*/
 IssmDouble* PetscVec::ToMPISerial(void){
-	
+
 	IssmDouble* vec_serial=NULL;
-	VecToMPISerial(&vec_serial, this->vector);
+	VecToMPISerial(&vec_serial, this->vector,IssmComm::GetComm());
 	return vec_serial;
 
Index: /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h	(revision 13975)
@@ -19,5 +19,4 @@
 #include "../../../include/include.h"
 
-
 /*}}}*/
 
@@ -31,13 +30,13 @@
 		#endif
 
-
-		/*PetscVec constructors, destructors {{{*/
+		/*PetscVec constructors, destructors*/
 		PetscVec();
 		PetscVec(int M,bool fromlocalsize=false);
+		PetscVec(int m,int M);
 		PetscVec(IssmDouble* buffer, int M);
 		PetscVec(Vec petsc_vec);
 		~PetscVec();
-		/*}}}*/
-		/*PetscVec specific routines {{{*/
+
+		/*PetscVec specific routines*/
 		void Echo(void);
 		void Assemble(void);
@@ -57,5 +56,4 @@
 		void PointwiseDivide(PetscVec* x,PetscVec* y);
 		IssmDouble Dot(PetscVec* vector);
-		/*}}}*/
 };
 
Index: /issm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp	(revision 13975)
@@ -3,5 +3,4 @@
  *  lower row and upper row from a matrix a cpu owns.
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -14,25 +13,25 @@
 #include "../../../shared/shared.h"
 
-void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range){
+void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,COMM comm){
 
 	/*externals :*/
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
+	int num_procs;
+
+	/*recover my_rank and num_procs:*/
+	MPI_Comm_size(comm,&num_procs);
+	MPI_Comm_rank(comm,&my_rank);
+
 	/*output: */
 	int lower_row,upper_row;
-	
-	/*intermediary :*/
-	int i;
-	int* allranges=NULL;
 
 	/*Gather all range values into allranges, for all nodes*/
-	allranges=xNew<int>(num_procs);
-	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
+	int* allranges=xNew<int>(num_procs);
+	MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,comm);
 
 	/*From all ranges, get lower row and upper row*/
 	lower_row=0;
 	upper_row=lower_row+allranges[0];
-	for (i=1;i<=my_rank;i++){
+	for(int i=1;i<=my_rank;i++){
 		lower_row=lower_row+allranges[i-1];
 		upper_row=upper_row+allranges[i];
Index: sm/trunk/src/c/toolkits/petsc/patches/ISFree.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISFree.cpp	(revision 13974)
+++ 	(revision )
@@ -1,28 +1,0 @@
-/*!\file:  ISFree.cpp
- * \brief wrapper to ISDestroy
- */ 
-
-#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 "petscmat.h"
-#include "petscksp.h"
-
-void ISFree(IS* pis){
-
-	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-	if(*pis)ISDestroy(*pis);
-	*pis=NULL;
-	#else
-	if(*pis)ISDestroy(pis);
-	*pis=NULL;
-	#endif
-
-}
-
Index: /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: convert InsertMode from ISSM to Petsc
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -11,12 +10,11 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 /*ISSM includes: */
 #include "../../toolkitsenums.h"
 #include "../../../shared/shared.h"
-
 
 InsertMode ISSMToPetscInsertMode(InsMode mode){
Index: /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: convert MatrixType from ISSM to Petsc
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -11,7 +10,7 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 /*ISSM includes: */
@@ -19,6 +18,5 @@
 #include "../../../shared/shared.h"
 
-
-MatType ISSMToPetscMatrixType(MatrixType type){
+const MatType ISSMToPetscMatrixType(MatrixType type){
 
 	switch(type){
Index: /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: convert NormMode from ISSM to Petsc
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -11,12 +10,11 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 /*ISSM includes: */
 #include "../../toolkitsenums.h"
 #include "../../../shared/shared.h"
-
 
 NormType ISSMToPetscNormMode(NormMode mode){
Index: /issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp	(revision 13975)
@@ -9,9 +9,8 @@
 #endif
 
-
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 void KSPFree(KSP* pksp){
@@ -26,3 +25,2 @@
 
 }
-
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp	(revision 13975)
@@ -9,9 +9,8 @@
 #endif
 
-
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscmat.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscmat.h>
+#include <petscksp.h>
 
 void MatFree(Mat* pmat){
@@ -26,3 +25,2 @@
 
 }
-
Index: sm/trunk/src/c/toolkits/petsc/patches/MatInvert.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatInvert.cpp	(revision 13974)
+++ 	(revision )
@@ -1,73 +1,0 @@
-/*!\file:  MatInvert.cpp
- * \brief  invert petsc matrix using LU factorization, and multiple right hand sides.
- */ 
-
-/*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
-
-#include "../../../shared/shared.h"
-#include "../../../include/include.h"
-
-void MatInvert(Mat* pinv, Mat matrix){
-
-
-	/*output: */
-	Mat inv=NULL;
-
-	/*intermediary: */
-	int M,N;
-	double sparsity=.001;
-
-	Mat factored_matrix=NULL;
-	Mat identity=NULL;
-	Vec diagonal=NULL;
-	KSP ksp=NULL;
-	PC pc=NULL;
-
-	/*Some checks: */
-	MatGetSize(matrix,&M,&N);
-	if(M!=N) _error_("trying to invert a non square matrix!");
-
-	/*Create identitiy matrix: */
-	identity=NewMat(M,N,sparsity);
-	diagonal=NewVec(M);
-	VecSet(diagonal,1.0);
-	MatDiagonalSet(identity,diagonal,INSERT_VALUES);
-	MatAssemblyBegin(identity,MAT_FINAL_ASSEMBLY);
-	MatAssemblyEnd(identity,MAT_FINAL_ASSEMBLY);
-	MatConvert(identity, MATMPIDENSE,MAT_REUSE_MATRIX,&identity);
-	
-	/*Initialize inverse: */
-	MatDuplicate(identity,MAT_DO_NOT_COPY_VALUES,&inv);
-
-	/* Compute X=inv(A) by MatMatSolve(), from tests in petsc test27 */
-	KSPCreate(PETSC_COMM_WORLD,&ksp);
-	KSPSetOperators(ksp,matrix,matrix,DIFFERENT_NONZERO_PATTERN);
-	KSPGetPC(ksp,&pc);
-	PCSetType(pc,PCLU);
-	KSPSetUp(ksp);
-	//PCGetFactoredMatrix(pc,&factored_matrix); //not found any replacement yet
-	MatMatSolve(factored_matrix,identity,inv);
-
-	/*Assemble inverse: */
-	MatAssemblyBegin(inv,MAT_FINAL_ASSEMBLY);
-	MatAssemblyEnd(inv,MAT_FINAL_ASSEMBLY);
-		
-	MatConvert(inv, MATMPIAIJ,MAT_REUSE_MATRIX,&inv);
-	
-	/*Free ressources:*/
-	MatFree(&identity);
-	VecFree(&diagonal);
-	#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-	KSPDestroy(ksp);
-	#else
-	KSPDestroy(&ksp);
-	#endif
-
-	/*Assign output pointers:*/
-	*pinv=inv;
-
-}
-
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp	(revision 13975)
@@ -10,15 +10,15 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 #include "../../../shared/shared.h"
 
 /*Function prototypes: */
-int MatMultCompatible(Mat A,Vec x);
-void VecRelocalize(Vec* outvector,Vec vector,int m);
+int MatMultCompatible(Mat A,Vec x,COMM comm);
+void VecRelocalize(Vec* outvector,Vec vector,int m,COMM comm);
 
-void MatMultPatch(Mat A,Vec X, Vec AX){ //same prototype as MatMult in Petsc
+void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm){ //same prototype as MatMult in Petsc
 
 	int m,n;
@@ -27,10 +27,10 @@
 	_assert_(A); _assert_(X);
 
-	if (MatMultCompatible(A,X)){
+	if (MatMultCompatible(A,X,comm)){
 		MatMult(A,X,AX); 
 	}
 	else{
 		MatGetLocalSize(A,&m,&n);;
-		VecRelocalize(&X_rel,X,n);
+		VecRelocalize(&X_rel,X,n,comm);
 		MatMult(A,X_rel,AX); ;
 		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
@@ -42,22 +42,25 @@
 }
 
-int MatMultCompatible(Mat A,Vec x){
-	
+int MatMultCompatible(Mat A,Vec x,COMM comm){
+
 	/*error management*/
-	
+
 	int local_m,local_n;
-	int lower_row,upper_row,range;
+	int range;
 	int result=1;
 	int sumresult;
-	extern int num_procs;
+	int num_procs;
+
+	/*recover num_procs:*/
+	MPI_Comm_size(comm,&num_procs);
 
 	MatGetLocalSize(A,&local_m,&local_n);;
 	VecGetLocalSize(x,&range);;
-	
+
 	if (local_n!=range)result=0;
-	
+
 	/*synchronize result: */
-	MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
-	MPI_Bcast(&sumresult,1,MPI_INT,0,MPI_COMM_WORLD);                
+	MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,comm );
+	MPI_Bcast(&sumresult,1,MPI_INT,0,comm);                
 	if (sumresult!=num_procs){
 		result=0;
@@ -69,5 +72,5 @@
 }
 
-void VecRelocalize(Vec* poutvector,Vec vector,int m){
+void VecRelocalize(Vec* poutvector,Vec vector,int m,COMM comm){
 
 	/*vector index and vector values*/
@@ -78,7 +81,7 @@
 	/*output: */
 	Vec outvector=NULL;
-	
+
 	/*Create outvector with local size m*/
-	VecCreate(PETSC_COMM_WORLD,&outvector); ; 
+	VecCreate(comm,&outvector); ; 
 	VecSetSizes(outvector,m,PETSC_DECIDE); ; 
 	VecSetFromOptions(outvector); ; 
Index: sm/trunk/src/c/toolkits/petsc/patches/MatPartition.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatPartition.cpp	(revision 13974)
+++ 	(revision )
@@ -1,138 +1,0 @@
-/*!\file: MatPartition.cpp
- * \brief partition matrix according to node sets
- */ 
-
-#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"
-
-#include "../../../shared/shared.h"
-#include "../../mpi/patches/mpipatches.h"
-
-int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
-		double* col_partition_vector,int col_partition_vector_size){
-
-	int i;
-	
-	/*Petsc matrix*/
-	int d_nz;
-	int o_nz;
-	int* node_rows=NULL;
-	int* node_cols=NULL;
-	int count;
-	IS col_index=NULL;
-	IS row_index=NULL;
-	int lower_row,upper_row,range;
-	int MA,NA; //matrixA dimensions
-	const char* type=NULL;
-	int csize;
-
-	/*output*/
-	Mat outmatrix=NULL;
-	
-	/*get input matrix size: */
-	MatGetSize(matrixA,&MA,&NA);
-
-    /*If one of the partitioning row or col vectors has a 0 dimension, we return a NILL matrix. Return it with the same type as matrixA.*/
-	
-    if ((row_partition_vector_size==0) || (col_partition_vector==0)){
-		MatGetType(matrixA,&type);
-		if (strcmp(type,"mpiaij")==0){
-			d_nz=0;
-			o_nz=0;
-			#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
-			MatCreateMPIAIJ(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,d_nz,PETSC_NULL,o_nz,PETSC_NULL,&outmatrix);
-			#endif
-		}
-		else if (strcmp(type,"mpidense")==0){
-			#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
-			MatCreateDense(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,PETSC_NULL,&outmatrix);
-			#else
-			MatCreateMPIDense(MPI_COMM_WORLD,PETSC_DETERMINE,PETSC_DETERMINE, 0,0,PETSC_NULL,&outmatrix);
-			#endif
-		}
-		else{
-			_error_("MatType " << type << " not supported yet");
-		}
-		/*Assemble*/
-		MatAssemblyBegin(outmatrix,MAT_FINAL_ASSEMBLY);
-		MatAssemblyEnd(outmatrix,MAT_FINAL_ASSEMBLY);
-	}
-	else{
-		/*Both vectors are non nill, use MatGetSubMatrix to condense out*/
-		/*Figure out which rows each node is going to get from matrix A.*/
-		MatGetOwnershipRange(matrixA,&lower_row,&upper_row);
-		upper_row--;
-		range=upper_row-lower_row+1;
-
-		count=0;
-		if (range){
-			node_rows=xNew<int>(range); //this is the maximum number of rows one node can extract.
-		
-			for (i=0;i<row_partition_vector_size;i++){
-				if ( ((int)(*(row_partition_vector+i))>=(lower_row+1)) && ((int)(*(row_partition_vector+i))<=(upper_row+1)) ){
-					*(node_rows+count)=(int)*(row_partition_vector+i)-1;
-					count++;
-				}
-			}
-		}
-		else{
-			count=0;
-		}
-		
-		/*Now each node has a node_rows vectors holding which rows they should extract from matrixA. Create an Index Set from node_rows.*/
-		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-		ISCreateGeneral(MPI_COMM_WORLD,count,node_rows,&row_index);
-		#else
-		ISCreateGeneral(MPI_COMM_WORLD,count,node_rows,PETSC_COPY_VALUES,&row_index);
-		#endif
-		
-		/*Same deal for columns*/
-		node_cols=xNew<int>(col_partition_vector_size);
-		for (i=0;i<col_partition_vector_size;i++){
-			*(node_cols+i)=(int)*(col_partition_vector+i)-1;
-		}
-		#if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
-		ISCreateGeneral(MPI_COMM_WORLD,col_partition_vector_size,node_cols,&col_index);
-		#else
-		ISCreateGeneral(MPI_COMM_WORLD,col_partition_vector_size,node_cols,PETSC_COPY_VALUES,&col_index);
-		#endif
-
-		/*Call MatGetSubMatrix*/
-		csize=DetermineLocalSize(col_partition_vector_size);
-		if(col_partition_vector_size==row_partition_vector_size){
-			#if _PETSC_MAJOR_ >= 3 
-			MatGetSubMatrix(matrixA,row_index,col_index,MAT_INITIAL_MATRIX,&outmatrix);
-			#else
-			MatGetSubMatrix(matrixA,row_index,col_index,count,MAT_INITIAL_MATRIX,&outmatrix);
-			#endif
-		}
-		else{
-			#if _PETSC_MAJOR_ >= 3 
-			MatGetSubMatrix(matrixA,row_index,col_index,MAT_INITIAL_MATRIX,&outmatrix);
-			#else
-			MatGetSubMatrix(matrixA,row_index,col_index,csize,MAT_INITIAL_MATRIX,&outmatrix);
-			#endif
-		}
-
-	}
-
-	/*Free ressources:*/
-	xDelete<int>(node_rows);
-	xDelete<int>(node_cols);
-	ISFree(&col_index);
-	ISFree(&row_index);
-
-	/*Assign output pointers:*/
-	*poutmatrix=outmatrix;
-	return 1;
-}
Index: /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp	(revision 13975)
@@ -9,14 +9,13 @@
 #endif
 
-
 #include "../petscincludes.h"
 #include "../../../shared/shared.h"
 
-void MatToSerial(double** poutmatrix,Mat matrix){
+void MatToSerial(double** poutmatrix,Mat matrix,COMM comm){
 
 	int i;
-	extern int my_rank;
-	extern int num_procs;
-	
+	int my_rank;
+	int num_procs;
+
 	/*Petsc variables*/
 	PetscInt lower_row,upper_row; 
@@ -28,8 +27,12 @@
 	double* local_matrix=NULL; /*matrix local to each node used for temporary holding matrix values*/
 	int buffer[3];
-	
+
+	/*recover my_rank and num_procs:*/
+	MPI_Comm_size(comm,&num_procs);
+	MPI_Comm_rank(comm,&my_rank);
+
 	/*Output*/
 	double* outmatrix=NULL;
-	
+
 	/*get matrix size: */
 	MatGetSize(matrix,&M,&N);
@@ -39,13 +42,13 @@
 	upper_row--; 
 	range=upper_row-lower_row+1;
-	
+
 	/*Local and global allocation*/
 	if (my_rank==0)outmatrix=xNew<double>(M*N);
-	
+
 	if (range){
 		local_matrix=xNew<double>(N*range);
 		idxm=xNew<int>(range);  
 		idxn=xNew<int>(N);  
-	 
+
 		for (i=0;i<N;i++){
 			*(idxn+i)=i;
@@ -54,5 +57,5 @@
 			*(idxm+i)=lower_row+i;
 		}
-	
+
 		MatGetValues(matrix,range,idxm,N,idxn,local_matrix);     
 	}
@@ -60,5 +63,5 @@
 	/*Now each node holds its local_matrix containing range rows. 
 	 * We send these rows to the matrix on node 0*/
-	
+
 	for (i=1;i<num_procs;i++){
 		if (my_rank==i){ 
@@ -66,10 +69,10 @@
 			buffer[1]=lower_row;
 			buffer[2]=range;
-			MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD);   
-			if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+			MPI_Send(buffer,3,MPI_INT,0,1,comm);   
+			if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,comm); 
 		}
 		if (my_rank==0){
-			MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
-			if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+			MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status); 
+			if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,comm,&status);
 		}
 	} 
@@ -78,5 +81,5 @@
 		memcpy(outmatrix,local_matrix,N*range*sizeof(double));
 	} 
-	
+
 	/*Assign output pointer: */
 	*poutmatrix=outmatrix;
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp	(revision 13975)
@@ -10,7 +10,7 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 #include "./petscpatches.h"
@@ -21,5 +21,5 @@
 
 /*NewMat(int M,int N){{{*/
-Mat NewMat(int M,int N){
+Mat NewMat(int M,int N,COMM comm){
 
 	/*output:*/
@@ -32,7 +32,7 @@
 
 	/*Determine local sizes: */
-	m=DetermineLocalSize(M);
-	n=DetermineLocalSize(N);
-	
+	m=DetermineLocalSize(M,comm);
+	n=DetermineLocalSize(N,comm);
+
 	nnz=(int)((double)M*(double)N*sparsity); //number of non zeros.
 	d_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
@@ -40,7 +40,7 @@
 
 	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
-	MatCreateAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
 	#else
-	MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
 	#endif
 
@@ -48,6 +48,6 @@
 }
 /*}}}*/
-/*NewMat(int M,int N,double sparsity){{{*/
-Mat NewMat(int M,int N,double sparsity){
+/*NewMat(int M,int N,double sparsity,COMM comm){{{*/
+Mat NewMat(int M,int N,double sparsity,COMM comm){
 
 	/*output:*/
@@ -60,7 +60,7 @@
 
 	/*Determine local sizes: */
-	m=DetermineLocalSize(M);
-	n=DetermineLocalSize(N);
-	
+	m=DetermineLocalSize(M,comm);
+	n=DetermineLocalSize(N,comm);
+
 	nnz=(int)((double)M*(double)N*sparsity); //number of non zeros.
 	d_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
@@ -69,11 +69,11 @@
 	#if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
 	if(sparsity==1){
-		MatCreateDense(MPI_COMM_WORLD,m,n,M,N,NULL,&outmatrix); 
+		MatCreateDense(comm,m,n,M,N,NULL,&outmatrix); 
 	}
 	else{
-		MatCreateAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+		MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
 	}
 	#else
-	MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
+	MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix); 
 	#endif
 
@@ -82,5 +82,5 @@
 /*}}}*/
 /*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{*/
-Mat NewMat(int M,int N,int connectivity,int numberofdofspernode){
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode,COMM comm){
 
 	/*output:*/
@@ -90,8 +90,11 @@
 	int    m,n;
 	int    d_nz,o_nz;
-	int    nnz;
 
 	#if _PETSC_MAJOR_ >= 3 
+	#ifdef _HAVE_PETSCDEV_
+	MatType type;
+	#else
 	const MatType type;
+	#endif
 	#else
 	MatType type;
@@ -99,6 +102,6 @@
 
 	/*Determine local sizes: */
-	m=DetermineLocalSize(M);
-	n=DetermineLocalSize(N);
+	m=DetermineLocalSize(M,comm);
+	n=DetermineLocalSize(N,comm);
 
 	/*Figure out number of non zeros per row: */
@@ -106,5 +109,5 @@
 	o_nz=(int)connectivity*numberofdofspernode/2;
 
-	MatCreate(MPI_COMM_WORLD,&outmatrix);
+	MatCreate(comm,&outmatrix);
 	MatSetSizes(outmatrix,m,n,M,N);
 	MatSetFromOptions(outmatrix);
@@ -112,5 +115,5 @@
 	/*preallocation  according to type: */
 	MatGetType(outmatrix,&type);
-	
+
 	#if _PETSC_MAJOR_ == 2 
 	if((strcmp(type,"mpiaij")==0) || (strcmp(type,"aijmumps")==0)){
Index: /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp	(revision 13975)
@@ -17,7 +17,6 @@
 #include "../../mpi/patches/mpipatches.h"
 
-Vec NewVec(int size,bool fromlocalsize){
+Vec NewVec(int size,COMM comm,bool fromlocalsize){
 
-	int ierr;
 	int local_size;
 
@@ -30,9 +29,9 @@
 	}
 	else{
-		local_size=DetermineLocalSize(size);
+		local_size=DetermineLocalSize(size,comm);
 	}
-	
-	VecCreate(PETSC_COMM_WORLD,&vector); 
-	
+
+	VecCreate(comm,&vector); 
+
 	VecSetSizes(vector,local_size,PETSC_DECIDE); 
 	VecSetFromOptions(vector); 
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp	(revision 13975)
@@ -2,5 +2,4 @@
  * \brief: convert a sparse or dense Petsc matrix into a matlab matrix
  */
-
 
 #ifdef HAVE_CONFIG_H
@@ -13,29 +12,23 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 /*Petsc includes: */
 #include "../../../shared/shared.h"
 
-
 void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat petsc_matrix){
 
-	int i,j,k;
-
 	/*output: */
+	int     i;
 	double* matrix=NULL;
 	int     rows,cols;
-
-	/*intermediary: */
-	int*    idxm=NULL;
-	int*    idxn=NULL;
 
 	/*Some needed information: */
 	MatGetSize(petsc_matrix,&rows,&cols);
 
-	idxm=xNew<int>(rows);
-	idxn=xNew<int>(cols);
+	int* idxm=xNew<int>(rows);
+	int* idxn=xNew<int>(cols);
 
 	for(i=0;i<rows;i++)idxm[i]=i;
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp	(revision 13975)
@@ -53,5 +53,4 @@
 	}
 
-
 	#if _PETSC_MAJOR_ >= 3 
 	PetscOptionsGetString(PETSC_NULL,"-pc_factor_mat_solver_package",&option[0],100,&flag);
@@ -61,5 +60,4 @@
 	#endif
 
-	
 	PetscOptionsGetString(PETSC_NULL,"-issm_option_solver",&option[0],100,&flag);
 	if (strcmp(option,"stokes")==0){
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp	(revision 13975)
@@ -10,7 +10,7 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 #include "./petscpatches.h"
@@ -20,5 +20,4 @@
 
 void PetscOptionsInsertMultipleString(char* options_string){
-
 
 	/*The list of options is going to be pairs of the type "-option option_value"*/
@@ -30,13 +29,9 @@
 	char* first=NULL;
 	char* second=NULL;
-	char* final=NULL;
 	size_t len;
-	int ignore_second;
 	int first_token=1;
-
 
 	PetscTokenCreate(options_string,' ',&token);
 	for (;;){
-		
 
 		/*Read next tokens*/
@@ -45,5 +40,5 @@
 		}
 		PetscTokenFind(token,&second);
-		
+
 		if (!first){
 			/*We are at the end of options*/
@@ -59,5 +54,5 @@
 			/*Reduce first to bare option value*/
 			PetscStrlen(first,&len);
-			while (len > 0 && (first[len-1] == ' ' || first[len-1] == 'n')) {
+			while (len > 0 && first[len-1] == ' ') {
 				len--; first[len] = 0;
 			}
@@ -70,5 +65,5 @@
 				/*Second is another option, ignore it*/
 				PetscStrlen(first,&len);
-				while (len > 0 && (first[len-1] == ' ' || first[len-1] == 'n')) {
+				while (len > 0 && first[len-1] == ' ' ) {
 					len--; first[len] = 0;
 				}
@@ -81,5 +76,5 @@
 				/*Second is 'first' option's value*/
 				PetscStrlen(second,&len);
-				while (len > 0 && (second[len-1] == ' ' || second[len-1] == 'n')) {
+				while (len > 0 && second[len-1] == ' ') {
 					len--; second[len] = 0;
 				}
Index: /issm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp	(revision 13975)
@@ -11,7 +11,7 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 #include "../../../shared/shared.h"
@@ -19,7 +19,5 @@
 void PetscVectorToDoubleVector(double** pvector, int* prows, Vec petsc_vector){
 
-	int     i;
 	int     rows;
-	int    *idxm   = NULL;
 	double *vector = NULL;
 
@@ -28,7 +26,7 @@
 		VecGetSize(petsc_vector,&rows);
 		if(rows){
-			idxm=xNew<int>(rows);
+			int* idxm=xNew<int>(rows);
 			vector=xNew<double>(rows);
-			for(i=0;i<rows;i++)idxm[i]=i;
+			for(int i=0;i<rows;i++)idxm[i]=i;
 			VecGetValues(petsc_vector,rows,idxm,vector);
 			xDelete<int>(idxm);
Index: sm/trunk/src/c/toolkits/petsc/patches/SerialToVec.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/SerialToVec.cpp	(revision 13974)
+++ 	(revision )
@@ -1,60 +1,0 @@
-/* \file SerialToVec.cpp
- * \brief: convert a serial vector on all cpus into a parallel 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"
-
-#include "../../../shared/shared.h"
-
-Vec  SerialToVec(double* vector,int vector_size){
-
-	int i;
-
-	/*output: */
-	Vec outvector=NULL;
-
-	/*petsc indices: */
-	int* idxn=NULL;
-	double* values=NULL;
-	int lower_row,upper_row,range;
-	
-		
-	/*Create parallel vector: */
-	outvector=NewVec(vector_size);
-
-	/*plug values from local vector into new parallel vector: */
-	VecGetOwnershipRange(outvector,&lower_row,&upper_row);
-	upper_row--;
-	range=upper_row-lower_row+1;    
-
-	if (range){
-		idxn=xNew<int>(range); 
-		values=xNew<double>(range);
-		for (i=0;i<range;i++){
-			idxn[i]=lower_row+i;
-			values[i]=vector[idxn[i]];
-		}
-
-		VecSetValues(outvector,range,idxn,values,INSERT_VALUES);
-	}
-
-
-	/*Assemble vector: */
-	VecAssemblyBegin(outvector);
-	VecAssemblyEnd(outvector);
-
-	/*Free ressources:*/
-	xDelete<int>(idxn);
-	xDelete<double>(values);
-
-	return outvector;
-}
Index: /issm/trunk/src/c/toolkits/petsc/patches/SolverEnum.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/SolverEnum.h	(revision 13975)
@@ -15,5 +15,3 @@
 } EXTERNALPACKAGES; 
 
-
 #endif //ifndef _SOLVERENUM_H_
-
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp	(revision 13975)
@@ -9,9 +9,8 @@
 #endif
 
-
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 void VecDuplicatePatch(Vec* output, Vec input){
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp	(revision 13975)
@@ -9,9 +9,8 @@
 #endif
 
-
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 void VecFree(Vec* pvec){
@@ -25,3 +24,2 @@
 
 }
-
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp	(revision 13975)
@@ -10,7 +10,7 @@
 
 /*Petsc includes: */
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
 
 #include "./petscpatches.h"
@@ -21,6 +21,4 @@
 void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size){
 
-	int i;
-	
 	/*Petsc matrix*/
 	int lower_row,upper_row,range;
@@ -29,10 +27,10 @@
 
 	/*Vector sizes: */
-	int MA,MB;
+	int MB;
 
 	VecGetSize(B,&MB);
 
 	/*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) ){
+	if ((row_partition_size !=MB) ){
 		_error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
 	}
@@ -47,15 +45,15 @@
 		idxm=xNew<int>(range);
 		values=xNew<double>(range);
-		for (i=0;i<range;i++){
-			*(idxm+i)=lower_row+i;
+		for(int i=0;i<range;i++){
+			idxm[i]=lower_row+i;
 		}
 		VecGetValues(B,range,idxm,values);
 		/*Now, modify idxm using the partition vector, and plug values into A*/
-		for (i=0;i<range;i++){
-			*(idxm+i)=(int)*(row_partition_vector+lower_row+i)-1; //-1 because partition vector comes from Matlab, where indices start at 1.
+		for(int i=0;i<range;i++){
+			idxm[i]=int(row_partition_vector[lower_row+i])-1; //-1 because partition vector comes from Matlab, where indices start at 1.
 		}
 		VecSetValues(A,range,idxm,values,INSERT_VALUES);
 	}
-	
+
 	/*Assemble vector*/
 	VecAssemblyBegin(A);
Index: sm/trunk/src/c/toolkits/petsc/patches/VecPartition.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecPartition.cpp	(revision 13974)
+++ 	(revision )
@@ -1,118 +1,0 @@
-/*!\file:  VecPartition.cpp
- * \brief  partition vector according to a node set
- */ 
-
-#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"
-
-#include "../../../shared/shared.h"
-
-void VecPartition(Vec* poutvector,Vec vectorA, double* row_partition_vector, int row_partition_vector_size,bool kffpartition){
-
-		
-	int i;
-	
-	/*Petsc matrix*/
-	int* node_rows=NULL;
-	double* values=NULL;
-	int count;
-	int lower_row,upper_row,range;
-
-	/*Input*/
-	int MA; //Vector dimension
-
-	/*output*/
-	Vec outvector=NULL;
-
-	
-	/*Get size of input vector: */
-	VecGetSize(vectorA,&MA);
-	
-    /*Condense out*/
-
-    /*If the partitioning row vector has a 0 dimension, we return a NILL vector*/
-    if (row_partition_vector_size==0){
-		VecCreate(PETSC_COMM_WORLD,&outvector);   
-		VecSetSizes(outvector,PETSC_DECIDE,0);
-		VecSetFromOptions(outvector);
-		
-		VecAssemblyBegin(outvector);
-		VecAssemblyEnd(outvector);
-	}
-	else{
-		/*Locally get values and build a new vector which is a subvector*/
-		
-		VecGetOwnershipRange(vectorA,&lower_row,&upper_row);
-		upper_row--;
-		range=upper_row-lower_row+1;
-
-		if (range){
-			node_rows=xNew<int>(range); //this is the maximum number of rows one node can extract.
-		
-			count=0;
-			for (i=0;i<row_partition_vector_size;i++){
-				if ( ((int)(*(row_partition_vector+i))>=(lower_row+1)) && ((int)(*(row_partition_vector+i))<=(upper_row+1)) ){
-					*(node_rows+count)=(int)*(row_partition_vector+i)-1;
-					count++;
-				}
-			}
-		}
-		else{
-			count=0;
-		}
-					
-     	if (count){
-			values=xNew<double>(count); //holder for the values to be extracted from vectorA
-		}
-		else{
-			xDelete<int>(node_rows); //count=0 means no values was condensed out for this node. null node_rows for use in VecGetValues.
-			values=NULL;
-		}
-
-		if (count){
-			VecGetValues(vectorA,count,node_rows,values);
-		}
-		
-		/*Ok, each node now have count values corresponding to the node_rows extracted values from vectorA.
-		 * From count and values, create a new vector*/
-		VecCreate(PETSC_COMM_WORLD,&outvector);
-		VecSetSizes(outvector,count,PETSC_DECIDE);
-		VecSetFromOptions(outvector);
-		VecGetOwnershipRange(outvector,&lower_row,&upper_row);
-
-		/*build new node_rows index.*/
-		if (count){
-			for (i=0;i<count;i++){
-				*(node_rows+i)=lower_row+i;
-			}
-		}
-		
-		/* outvector should not be partitioned like it was previously, but according to row_partition_vector_size, this in case we 
-		 * are running with the special kffpartition schema: */
-		if(kffpartition){
-			VecFree(&outvector);
-			outvector=NewVec(row_partition_vector_size);
-		}
-
-		if (count){
-			VecSetValues(outvector,count,node_rows,values,INSERT_VALUES);
-		}
-		
-		/*Assemble vector*/
-		VecAssemblyBegin(outvector);
-		VecAssemblyEnd(outvector);
-	}
-	
-	/*Assign output pointers:*/
-	*poutvector=outvector;
-	xDelete<int>(node_rows);
-	xDelete<double>(values);
-}
Index: /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp	(revision 13975)
@@ -9,13 +9,12 @@
 #endif
 
-
 #include "../petscincludes.h"
 #include "../../../shared/shared.h"
 
-int VecToMPISerial(double** pgathered_vector, Vec vector){
-	
+int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm){
+
 	int i;
-	extern int num_procs; 
-	extern int my_rank;
+	int num_procs; 
+	int my_rank;
 
 	/*Petsc*/
@@ -25,5 +24,5 @@
 	int * idxn=NULL; 
 	int buffer[3];
-	
+
 	/*intermediary results*/
 	double* local_vector=NULL;
@@ -31,7 +30,11 @@
 	/*input*/
 	int vector_size;
-	
+
 	/*Output*/
 	double* gathered_vector=NULL; //Global vector holding the final assembled vector on all nodes.
+
+	/*recover my_rank and num_procs*/
+	MPI_Comm_size(comm,&num_procs);
+	MPI_Comm_rank(comm,&my_rank);
 
 	VecGetSize(vector,&vector_size);
@@ -43,5 +46,5 @@
 	/*Allocate gathered vector on all nodes .*/
 	gathered_vector=xNew<double>(vector_size);
-	
+
 	/*Allocate local vectors*/
 	VecGetOwnershipRange(vector,&lower_row,&upper_row);
@@ -66,10 +69,10 @@
 			buffer[1]=lower_row;
 			buffer[2]=range;
-			MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD);  
-			if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,MPI_COMM_WORLD); 
+			MPI_Send(buffer,3,MPI_INT,0,1,comm);  
+			if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,comm); 
 		}
 		if (my_rank==0){
-			MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status); 
-			if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
+			MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status); 
+			if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,comm,&status);
 		}
 	}
@@ -81,13 +84,13 @@
 
 	/*Now, broadcast gathered_vector from node 0 to other nodes: */
-	MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,MPI_COMM_WORLD);
+	MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,comm);
 
 	/*Assign output pointers: */
 	*pgathered_vector=gathered_vector;
-	
+
 	/*free ressources: */
 	xDelete<int>(idxn);
 	xDelete<double>(local_vector);
-	
+
 	return 1;
 }
Index: sm/trunk/src/c/toolkits/petsc/patches/VecTranspose.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/VecTranspose.cpp	(revision 13974)
+++ 	(revision )
@@ -1,66 +1,0 @@
-/*! \file VecTranspose.cpp
- *  \brief: transpose of a petsc vector
- */
-
-#include "./petscpatches.h"
-#include "../../../shared/shared.h"
-
-int VecTranspose(Vec* ptvector,Vec vector){
-
-	int i;
-	int size;
-	int lower_row,upper_row,range;
-	
-	int* idxm=NULL;
-	double* values=NULL;
-
-	int* tidxm=NULL;
-	double* tvalues=NULL;
-	
-	/*output: */
-	Vec tvector=NULL;
-
-	/*Get size of input vector: */
-	VecGetSize(vector,&size);
-	
-	/*Create new vector of same size: */
-	tvector=NewVec(size);
-
-	/*Extract values locally from input vector: */
-	VecGetOwnershipRange(vector,&lower_row,&upper_row);
-	upper_row--;
-	range=upper_row-lower_row+1;    
-
-	if (range){
-		idxm=xNew<int>(range); 
-		tidxm=xNew<int>(range); 
-		for (i=0;i<range;i++){
-			*(idxm+i)=lower_row+i;
-		} 
-		values=xNew<double>(range);
-		tvalues=xNew<double>(range);
-		
-		VecGetValues(vector,range,idxm,values);
-		
-		/*Transfer values into tidxm, and idxm into tvalues: */
-		for (i=0;i<range;i++){
-			tidxm[i]=(int)values[i];
-			tvalues[i]=(double)idxm[i];
-		}
-		VecSetValues(tvector,range,tidxm,tvalues,INSERT_VALUES);
-	}
-
-	/*Assemble: */
-	VecAssemblyBegin(tvector);
-	VecAssemblyEnd(tvector);
-
-	/*Free ressources: */
-	xDelete<int>(idxm);
-	xDelete<double>(values);
-	xDelete<int>(tidxm);
-	xDelete<double>(tvalues);
-
-	/*Assign output pointers: */
-	*ptvector=tvector;
-	return 1;
-}
Index: /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h	(revision 13975)
@@ -6,40 +6,37 @@
 #define _PETSC_PATCHES_H_
 
-#include "petscmat.h"
-#include "petscvec.h"
-#include "petscksp.h"
-#include "petscsys.h"
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
+#include <petscsys.h>
 
 #include "./SolverEnum.h"
 #include "../../toolkitsenums.h"
+#include "../../../include/types.h"
 
 class Parameters;
 
-Vec NewVec(int size,bool fromlocalsize=false);
-Mat NewMat(int M,int N);
-Mat NewMat(int M,int N,double sparsity);
-Mat NewMat(int M,int N,int connectivity,int numberofdofspernode);
+Vec NewVec(int size,COMM comm,bool fromlocalsize=false);
+Mat NewMat(int M,int N,COMM comm);
+Mat NewMat(int M,int N,double sparsity,COMM comm);
+Mat NewMat(int M,int N,int connectivity,int numberofdofspernode, COMM comm);
 
-int VecTranspose(Vec* tvector,Vec vector);
-int VecToMPISerial(double** pgathered_vector, Vec vector);
-void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range);
+int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm);
 void MatFree(Mat* pmat);
 void ISFree(IS* pis);
 void VecFree(Vec* pvec);
 void KSPFree(KSP* pksp);
-void VecPartition(Vec* poutvector,Vec vectorA, double* row_partition_vector, int row_partition_vector_size,bool kffpartitioning);
 int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
 		double* col_partition_vector,int col_partition_vector_size);
-void MatInvert(Mat* pInv, Mat Matrix);
 void PetscOptionsInsertMultipleString(char* options_string);
 void PetscOptionsDetermineSolverType(int* psolver_type);
 void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size);
-void MatMultPatch(Mat A,Vec X, Vec AX);
-void MatToSerial(double** poutmatrix,Mat matrix);
+void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm);
+void MatToSerial(double** poutmatrix,Mat matrix,COMM comm);
 void VecDuplicatePatch(Vec* output, Vec input);
 Vec  SerialToVec(double* vector,int vector_size);
 InsertMode ISSMToPetscInsertMode(InsMode mode);
 NormType ISSMToPetscNormMode(NormMode mode);
-MatType ISSMToPetscMatrixType(MatrixType type);
+const MatType ISSMToPetscMatrixType(MatrixType type);
 
 void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat matrix);
Index: /issm/trunk/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp	(revision 13975)
@@ -3,5 +3,4 @@
 */
 #include <math.h>
-
 
 #include "../../../shared/shared.h"
@@ -10,5 +9,5 @@
 
 int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs){
-	
+
 	int nprows,npcols;
 	int last_diff;
@@ -40,9 +39,8 @@
 int PrimeDecomp(int** pdecomp,int* pdecomp_size,int input){
 
-	int* decomp=NULL;
 	int prime_factor;
 	int i;
 
-	decomp=xNew<int>(input);
+	int* decomp=xNew<int>(input);
 	*decomp=input;
 	for (i=0;i<input;i++){
@@ -65,5 +63,5 @@
 */
 int SmallestPrimeFactor(int* output,int input){
-	
+
 	int found=0;
 	int i;
Index: /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp	(revision 13975)
@@ -14,17 +14,17 @@
 
 void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,MPI_Comm* pcomm_2d);
-	
-int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con){ 
+
+int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm){ 
 	/*inv_A does not yet exist, inv_A was just allocated, that's all*/
 
 	/*Error management*/
-	int i,j;
+	int i;
 
 	/*input*/
 	int mA,nA;
 	int local_mA,local_nA;
-	int lower_row,upper_row,range,this_range,this_lower_row;
+	int lower_row,upper_row;
 	MatType type;
-	
+
 	/*Plapack: */
 	MPI_Datatype   datatype;
@@ -36,13 +36,8 @@
 	int nb,nb_alg;
 	int nprows,npcols;
-	int initialized=0;
 
 	/*Petsc to Plapack: */
 	double    *arrayA=NULL;
 	int* idxnA=NULL;
-	int d_nz,o_nz;
-	
-	/*Feedback to client*/
-	int computation_status;  
 
 	/*Verify that A is square*/
@@ -76,5 +71,5 @@
 	if(PLA_Initialized(NULL)==TRUE)PLA_Finalize();
 	/* Create a 2D communicator */
-	PLA_Comm_1D_to_2D(MPI_COMM_WORLD,nprows,npcols,&comm_2d); 
+	PLA_Comm_1D_to_2D(comm,nprows,npcols,&comm_2d); 
 
 	/*Initlialize plapack: */
@@ -92,5 +87,5 @@
 	/* Set the datatype */
 	datatype = MPI_DOUBLE;
-	
+
 	/* Copy A into a*/
 	PLA_Matrix_create(datatype,mA,nA,templ,PLA_ALIGN_FIRST,PLA_ALIGN_FIRST,&a);  
@@ -100,5 +95,4 @@
 	MatGetOwnershipRange(*A,&lower_row,&upper_row);
 	upper_row--; 
-	range=upper_row-lower_row+1;
 	arrayA = xNew<double>(nA);
 	idxnA  = xNew<int>(nA);
@@ -127,5 +121,5 @@
 	xDelete<double>(arrayA);
 	xDelete<int>(idxnA);
-	
+
 	/*Finalize PLAPACK*/
 	PLA_Finalize();
Index: /issm/trunk/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 13974)
+++ /issm/trunk/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp	(revision 13975)
@@ -6,10 +6,9 @@
 #include "../plapackincludes.h"
 
-int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb){
+int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb,COMM comm){
 
-	
 	int i;
 
-	int lower_row,upper_row,range;
+	int lower_row,upper_row;
 	int* row_nodes=NULL;
 	int* col_nodes=NULL;
@@ -22,5 +21,4 @@
 	double* local_buffer=NULL;
 
-
 	/*Create matrix A (right now, we just have an allocated pointer A*/
 	if (strcasecmp_eq(type,MATMPIAIJ)){
@@ -28,14 +26,13 @@
 		d_nz=nA/2;
 		o_nz=nA/2;
-		MatCreateMPIAIJ(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
+		MatCreateMPIAIJ(comm,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
 	}
 	else if(strcasecmp_eq(type,MATMPIDENSE)){
-		MatCreateMPIDense(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,PETSC_NULL,A); 
+		MatCreateMPIDense(comm,local_mA,local_nA, mA,nA,PETSC_NULL,A); 
 	}
-	
+
 	MatGetOwnershipRange(*A,&lower_row,&upper_row);
 	upper_row--;
-	range=upper_row-lower_row+1;
-	
+
 	/*Build the Plapack row and column indices corresponding to the local_buffer stored in a. 
 	  We need those indices to directly plug local_buffer into the Petsc matrix A. We do not 
@@ -43,5 +40,5 @@
 	  problem size becomes big. We rely therefore on MatAssembly from Petsc to gather the plapack 
 	  matrix into a Petsc Matrix.*/
-	
+
 	/*Vector physically based block cyclic distribution: */
 	row_nodes=xNew<int>(mA);
@@ -82,5 +79,5 @@
 	/*Get local buffer: */
 	PLA_Obj_local_buffer(a,(void**)&local_buffer);
-	
+
 	/*Insert into invA matrix. Use col oriented insertion, for Plapack is column oriented*/
 	MatSetOption(*A,MAT_COLUMN_ORIENTED);
Index: /issm/trunk/src/c/toolkits/plapack/patches/plapackpatches.h
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/plapack/patches/plapackpatches.h	(revision 13975)
@@ -6,6 +6,6 @@
 #define _PLAPACK_PATCHES_H_
 
-int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con);
-int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb);
+int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm);
+int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb,COMM comm);
 int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs);
 
Index: /issm/trunk/src/c/toolkits/plapack/plapackincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/plapack/plapackincludes.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/plapack/plapackincludes.h	(revision 13975)
@@ -12,6 +12,5 @@
 #endif
 
-
-#include "PLA.h"
+#include <PLA.h>
 
 /* missing Plapack prototypes: */
@@ -20,8 +19,6 @@
 /*our own patches: */
 #ifdef _HAVE_PETSC_
-#include "patches/petscpatches.h"
+#include "./patches/petscpatches.h"
 #endif
 
-
 #endif
-
Index: sm/trunk/src/c/toolkits/python/pythonincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/python/pythonincludes.h	(revision 13974)
+++ 	(revision )
@@ -1,35 +1,0 @@
-/* \file pythonincludes.h
- * \brief all includes for PYTHON layer
- */
-
-#ifndef _PYTHON_INCLUDES_H_
-#define _PYTHON_INCLUDES_H_
-
-
-#ifdef HAVE_CONFIG_H
-	#include <config.h>
-#else
-#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#if _PYTHON_MAJOR_ == 2
-#undef NPY_NO_DEPRECATED_API
-#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
-#else
-#define NPY_NO_DEPRECATED_API 
-#endif
-
-#include "Python.h"
-#include "arrayobject.h"
-
-#ifdef _HAVE_BOOST_
-using namespace std;
-#include <boost/python/def.hpp>
-#include <boost/python.hpp>
-#include <boost/python/module.hpp>
-using namespace boost::python;
-typedef boost::python::numeric::array pyArray;
-#endif
-
-
-#endif
Index: /issm/trunk/src/c/toolkits/scalapack/FortranMapping.h
===================================================================
--- /issm/trunk/src/c/toolkits/scalapack/FortranMapping.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/scalapack/FortranMapping.h	(revision 13975)
@@ -5,5 +5,4 @@
  *     Description:  Fortran to C define to use Scalapack in a C program
  */
-
 
 /*We transform every call to Fortran functions into their real symbolic name in the Scalapack, Blacs, Lapack and Blas libraries. 
@@ -22,5 +21,4 @@
 #define PDGETRF(...) pdgetrf_(__VA_ARGS__)
 #define PDGETRI(...) pdgetri_(__VA_ARGS__)
-
 
 /*Here, we clobber the fortran definition of these routines. Remember, every variable in fortran is passed by a pointer, and the 
Index: /issm/trunk/src/c/toolkits/toolkits.h
===================================================================
--- /issm/trunk/src/c/toolkits/toolkits.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/toolkits.h	(revision 13975)
@@ -10,8 +10,4 @@
 #else
 #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
-#endif
-
-#ifdef _HAVE_PYTHON_
-#include "./python/pythonincludes.h"
 #endif
 
@@ -31,4 +27,3 @@
 #include "./toolkitsenums.h"
 #include "./issm/issmtoolkit.h"
-
 #endif
Index: /issm/trunk/src/c/toolkits/triangle/triangleincludes.h
===================================================================
--- /issm/trunk/src/c/toolkits/triangle/triangleincludes.h	(revision 13974)
+++ /issm/trunk/src/c/toolkits/triangle/triangleincludes.h	(revision 13975)
@@ -11,4 +11,3 @@
 #endif //#ifdef _C_
 
-
 #endif
Index: /issm/trunk/src/dox/issm.dox
===================================================================
--- /issm/trunk/src/dox/issm.dox	(revision 13974)
+++ /issm/trunk/src/dox/issm.dox	(revision 13975)
@@ -46,17 +46,17 @@
 </th>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">508</td><td  bgcolor=#FFFFFF style="text-align:right;">14595</td><td  bgcolor=#FFFFFF style="text-align:right;">16762</td><td  bgcolor=#FFFFFF style="text-align:right;">56036</td><td  bgcolor=#FFFFFF style="text-align:right;">87393</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">505</td><td  bgcolor=#FFFFFF style="text-align:right;">14316</td><td  bgcolor=#FFFFFF style="text-align:right;">16564</td><td  bgcolor=#FFFFFF style="text-align:right;">56522</td><td  bgcolor=#FFFFFF style="text-align:right;">87402</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">925</td><td  bgcolor=#C6E2FF style="text-align:right;">6851</td><td  bgcolor=#C6E2FF style="text-align:right;">13228</td><td  bgcolor=#C6E2FF style="text-align:right;">30468</td><td  bgcolor=#C6E2FF style="text-align:right;">50547</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">913</td><td  bgcolor=#C6E2FF style="text-align:right;">6625</td><td  bgcolor=#C6E2FF style="text-align:right;">13054</td><td  bgcolor=#C6E2FF style="text-align:right;">30160</td><td  bgcolor=#C6E2FF style="text-align:right;">49839</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">378</td><td  bgcolor=#FFFFFF style="text-align:right;">2758</td><td  bgcolor=#FFFFFF style="text-align:right;">2612</td><td  bgcolor=#FFFFFF style="text-align:right;">9818</td><td  bgcolor=#FFFFFF style="text-align:right;">15188</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">388</td><td  bgcolor=#FFFFFF style="text-align:right;">3069</td><td  bgcolor=#FFFFFF style="text-align:right;">2983</td><td  bgcolor=#FFFFFF style="text-align:right;">11855</td><td  bgcolor=#FFFFFF style="text-align:right;">17907</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">997</td><td  bgcolor=#C6E2FF style="text-align:right;">80</td><td  bgcolor=#C6E2FF style="text-align:right;">8259</td><td  bgcolor=#C6E2FF style="text-align:right;">9336</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">6</td><td  bgcolor=#C6E2FF style="text-align:right;">1052</td><td  bgcolor=#C6E2FF style="text-align:right;">79</td><td  bgcolor=#C6E2FF style="text-align:right;">8993</td><td  bgcolor=#C6E2FF style="text-align:right;">10124</td>
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">53</td><td  bgcolor=#FFFFFF style="text-align:right;">400</td><td  bgcolor=#FFFFFF style="text-align:right;">610</td><td  bgcolor=#FFFFFF style="text-align:right;">1424</td><td  bgcolor=#FFFFFF style="text-align:right;">2434</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">81</td><td  bgcolor=#FFFFFF style="text-align:right;">2677</td><td  bgcolor=#FFFFFF style="text-align:right;">3936</td><td  bgcolor=#FFFFFF style="text-align:right;">5169</td><td  bgcolor=#FFFFFF style="text-align:right;">11782</td>
 </tr>
 <tr>
@@ -64,8 +64,8 @@
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">21</td><td  bgcolor=#FFFFFF style="text-align:right;">23</td><td  bgcolor=#FFFFFF style="text-align:right;">240</td><td  bgcolor=#FFFFFF style="text-align:right;">284</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">5</td><td  bgcolor=#FFFFFF style="text-align:right;">58</td><td  bgcolor=#FFFFFF style="text-align:right;">81</td><td  bgcolor=#FFFFFF style="text-align:right;">268</td><td  bgcolor=#FFFFFF style="text-align:right;">407</td>
 </tr>
 <tr>
-<th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">5</td><td  bgcolor=#C6E2FF style="text-align:right;">47</td><td  bgcolor=#C6E2FF style="text-align:right;">75</td><td  bgcolor=#C6E2FF style="text-align:right;">239</td><td  bgcolor=#C6E2FF style="text-align:right;">361</td>
+<th  bgcolor=#C6E2FF style="text-align:left;"> Perl </th><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">21</td><td  bgcolor=#C6E2FF style="text-align:right;">23</td><td  bgcolor=#C6E2FF style="text-align:right;">240</td><td  bgcolor=#C6E2FF style="text-align:right;">284</td>
 </tr>
 <tr>
@@ -76,5 +76,5 @@
 </tr>
 <tr>
-<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1890</td><td  bgcolor=#FFFFFF style="text-align:right;">25787</td><td  bgcolor=#FFFFFF style="text-align:right;">33397</td><td  bgcolor=#FFFFFF style="text-align:right;">106984</td><td  bgcolor=#FFFFFF style="text-align:right;">166168</td>
+<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1912</td><td  bgcolor=#FFFFFF style="text-align:right;">27936</td><td  bgcolor=#FFFFFF style="text-align:right;">36727</td><td  bgcolor=#FFFFFF style="text-align:right;">113707</td><td  bgcolor=#FFFFFF style="text-align:right;">178370</td>
 </tr>
 </table>
Index: /issm/trunk/src/m/Makefile.am
===================================================================
--- /issm/trunk/src/m/Makefile.am	(revision 13974)
+++ /issm/trunk/src/m/Makefile.am	(revision 13975)
@@ -3,4 +3,5 @@
 #find . -type d -exec ls -d {} \;
 
+if WRAPPERS
 bin_SCRIPTS= ./qmu/*.m \
 				 ./qmu/setupdesign/*.m \
@@ -49,2 +50,3 @@
 				 ./solvers/*.m \
 				 ./materials/*.m
+endif
Index: /issm/trunk/src/m/array/array_numel.m
===================================================================
--- /issm/trunk/src/m/array/array_numel.m	(revision 13974)
+++ /issm/trunk/src/m/array/array_numel.m	(revision 13975)
@@ -17,5 +17,5 @@
         inum=numel(varargin{iarg});
     end
-    
+
     if ~isequal(inum,1)
         if isequal(anum,1)
Index: /issm/trunk/src/m/array/array_size.m
===================================================================
--- /issm/trunk/src/m/array/array_size.m	(revision 13974)
+++ /issm/trunk/src/m/array/array_size.m	(revision 13975)
@@ -17,5 +17,5 @@
         isize=size(varargin{iarg});
     end
-    
+
     if ~isequal(isize,[1 1])
         if isequal(asize,[1 1])
Index: /issm/trunk/src/m/array/str2int.m
===================================================================
--- /issm/trunk/src/m/array/str2int.m	(revision 13974)
+++ /issm/trunk/src/m/array/str2int.m	(revision 13975)
@@ -5,5 +5,5 @@
 %  function [aint]=str2int(astr,cfl)
 %
-function [aint]=str2int(astr,cfl);
+function [aint]=str2int(astr,cfl)
 
 aint=[];
@@ -44,3 +44,2 @@
 
 end
-
Index: /issm/trunk/src/m/array/struc_desc.m
===================================================================
--- /issm/trunk/src/m/array/struc_desc.m	(revision 13974)
+++ /issm/trunk/src/m/array/struc_desc.m	(revision 13975)
@@ -22,5 +22,5 @@
         desc=cellstr(varargin{iarg});
     end
-    
+
     for i=1:length(desc)
         sarrayoi=struc_desci(sarray,desc{i});
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13974)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m	(revision 13975)
@@ -58,5 +58,5 @@
 	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
+		md.basalforcings.geothermalflux=50.*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
 	end
 else
Index: /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 13975)
+++ /issm/trunk/src/m/boundaryconditions/SetIceSheetBC.py	(revision 13975)
@@ -0,0 +1,67 @@
+import os
+import numpy
+from ContourToMesh import *
+
+def 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=numpy.nonzero(md.mesh.vertexonboundary)
+	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvx[pos]=0
+	md.diagnostic.spcvy[pos]=0
+	md.diagnostic.spcvz[pos]=0
+	md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+
+	#Dirichlet Values
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		print "      boundary conditions for diagnostic model: spc set as observed velocities"
+		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print "      boundary conditions for diagnostic model: spc set as zero"
+
+	#segment on neumann (Ice Front) -> none
+	if md.mesh.dimension==2:
+		md.diagnostic.icefront=numpy.zeros((0,4))
+	else:
+		md.diagnostic.icefront=numpy.zeros((0,6))
+
+	#Create zeros basal melting rate and surface mass balance if not specified
+	if numpy.all(numpy.isnan(md.surfaceforcings.precipitation)) and (md.surfaceforcings.ispdd==1):
+		md.surfaceforcings.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
+		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,1))
+		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,1))
+		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,1))
+		print "      no balancethickness.thickening_rate specified: values set as zero"
+
+	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+
+	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
+		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
+			md.basalforcings.geothermalflux=50.*10**-3*numpy.ones((md.mesh.numberofvertices,1))    #50 mW/m^2
+	else:
+		print "      no thermal boundary conditions created: no observed temperature found"
+
+	return md
+
Index: /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13974)
+++ /issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py	(revision 13975)
@@ -1,4 +1,5 @@
 import os
 import numpy
+from ContourToMesh import *
 
 def SetIceShelfBC(md,icefrontfile=''):
@@ -6,5 +7,5 @@
 	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
+	   Neumann BC are used on the ice front (an ARGUS contour around the ice front
 	   must be given in input)
 	   Dirichlet BC are used elsewhere for diagnostic
@@ -24,44 +25,49 @@
 		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)
+		[nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),icefrontfile,'node',2)
+		nodeonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1)).astype(float)
 	else:
-		nodeonicefront=numpy.zeros(md.mesh.numberofvertices)
+		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)
+	pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]
+	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 	md.diagnostic.spcvx[pos]=0
 	md.diagnostic.spcvy[pos]=0
 	md.diagnostic.spcvz[pos]=0
-	md.diagnostic.referential=float('NaN')*numpy.ones((md.mesh.numberofvertices,6))
+	md.diagnostic.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'
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		#reshape to rank-2 if necessary to match spc arrays
+		if numpy.ndim(md.inversion.vx_obs)==1:
+			md.inversion.vx_obs=md.inversion.vx_obs.reshape(-1,1)
+		if numpy.ndim(md.inversion.vy_obs)==1:
+			md.inversion.vy_obs=md.inversion.vy_obs.reshape(-1,1)
+		print "      boundary conditions for diagnostic model: spc set as observed velocities"
 		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
 		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
 	else:
-		print '      boundary conditions for diagnostic model: spc set as zero'
+		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]
+	pos=numpy.nonzero(numpy.logical_or(nodeonicefront[md.mesh.segments[:,0].astype(int)-1],nodeonicefront[md.mesh.segments[:,1].astype(int)-1]))[0]
 	if   md.mesh.dimension==2:
 		pressureload=md.mesh.segments[pos,:]
 	elif md.mesh.dimension==3:
 #		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
-		pressureload_layer1=numpy.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_layer1=numpy.hstack((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]))
 		pressureload=numpy.zeros((0,5))
 		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)
+			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d))))
 
 	#Add water or air enum depending on the element
 #	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
-	pressureload=numpy.concatenate((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape((-1,1))),axis=1)
+	pressureload=numpy.hstack((pressureload,1.*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape(-1,1)))
 
 	#plug onto model
@@ -70,28 +76,28 @@
 	#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'
+		md.surfaceforcings.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
+		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'
+		md.surfaceforcings.mass_balance=numpy.zeros((md.mesh.numberofvertices,1))
+		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'
+		md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+		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.balancethickness.thickening_rate=numpy.zeros((md.mesh.numberofvertices,1))
+		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)
+	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 
-	if numpy.size(md.initialization.temperature)==md.mesh.numberofvertices:
-		md.thermal.spctemperature=float('NaN')*numpy.ones(md.mesh.numberofvertices)
+	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
+		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
 #		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)
+		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
+			md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
 	else:
-		print '      no thermal boundary conditions created: no observed temperature found'
+		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 13974)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m	(revision 13975)
@@ -53,5 +53,5 @@
 
 md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
-pos=find(md.mesh.vertexonboundary); 
+pos=find(md.mesh.vertexonboundary);
 md.hydrology.spcwatercolumn(pos,1)=1;
 
@@ -73,5 +73,4 @@
 %plug onto model
 md.diagnostic.icefront=pressureload;
-
 
 %Create zeros basalforcings and surfaceforcings
@@ -101,5 +100,5 @@
 	if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
 		md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
-		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50*10^-3; %50mW/m2
+		md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50.*10.^-3; %50mW/m2
 	end
 else
Index: /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py
===================================================================
--- /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 13975)
+++ /issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.py	(revision 13975)
@@ -0,0 +1,111 @@
+import os
+import numpy
+from ContourToMesh import *
+
+def SetMarineIceSheetBC(md,icefrontfile=''):
+	"""
+	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 icefrontfile:
+		#User provided Front.exp, use it
+		if not os.path.exists(icefrontfile):
+			raise IOError("SetMarineIceSheetBC error message: ice front file '%s' not found." % icefrontfile)
+		[nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),icefrontfile,'node',2)
+		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1)).astype(float)
+	else:
+		#Guess where the ice front is
+		vertexonfloatingice=numpy.zeros((md.mesh.numberofvertices))
+		vertexonfloatingice[md.mesh.elements[numpy.nonzero(md.mask.elementonfloatingice),:].astype(int)-1]=1
+		vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,vertexonfloatingice).astype(float)
+
+#	pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
+	pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(vertexonicefront)))[0]
+	if not numpy.size(pos):
+		print "SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually."
+
+	md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.diagnostic.spcvx[pos]=0
+	md.diagnostic.spcvy[pos]=0
+	md.diagnostic.spcvz[pos]=0
+	md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+
+	#Dirichlet Values
+	if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
+		print "      boundary conditions for diagnostic model: spc set as observed velocities"
+		md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
+		md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
+	else:
+		print "      boundary conditions for diagnostic model: spc set as zero"
+
+	md.hydrology.spcwatercolumn=numpy.zeros((md.mesh.numberofvertices,2))
+	pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
+	md.hydrology.spcwatercolumn[pos,0]=1
+
+	#segment on Neumann (Ice Front)
+#	pos=find(vertexonicefront(md.mesh.segments(:,1)) | vertexonicefront(md.mesh.segments(:,2)));
+	pos=numpy.nonzero(numpy.logical_or(vertexonicefront[md.mesh.segments[:,0].astype(int)-1],vertexonicefront[md.mesh.segments[:,1].astype(int)-1]))[0]
+	if   md.mesh.dimension==2:
+		pressureload=md.mesh.segments[pos,:]
+	elif md.mesh.dimension==3:
+#		pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
+		pressureload_layer1=numpy.hstack((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]))
+		pressureload=numpy.zeros((0,5))
+		for i in xrange(1,md.mesh.numberoflayers):
+#			pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
+			pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d))))
+
+	#Add water or air enum depending on the element
+#	pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))+ 0*md.mask.elementongroundedice(pressureload(:,end))];
+	pressureload=numpy.hstack((pressureload,1.*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape(-1,1)+0.*md.mask.elementongroundedice[pressureload[:,-1].astype('int')-1].reshape(-1,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,1))
+		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,1))
+		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,1))
+		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,1))
+		print "      no balancethickness.thickening_rate specified: values set as zero"
+
+	md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+	md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+
+	if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
+		md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+#		pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
+		pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
+		md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
+		if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
+			md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
+			md.basalforcings.geothermalflux[numpy.nonzero(md.mask.vertexongroundedice)]=50.*10.**-3    #50mW/m2
+	else:
+		print "      no thermal boundary conditions created: no observed temperature found"
+
+	return md
+
Index: /issm/trunk/src/m/classes/autodiff.m
===================================================================
--- /issm/trunk/src/m/classes/autodiff.m	(revision 13974)
+++ /issm/trunk/src/m/classes/autodiff.m	(revision 13975)
@@ -9,4 +9,5 @@
 		dependents   = {};
 		independents = {};
+		driver       = 'fos_forward';
 	end
 	methods
@@ -24,44 +25,179 @@
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
 
-		%Early return 
-		if ~obj.isautodiff, return; end
+			%Early return 
+			if ~obj.isautodiff, return; end
+
+			%Driver value:
+			md = checkfield(md,'autodiff.driver','values',{'fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'});
+
+			%go through our dependents and independents and check consistency: 
+			for i=1:numel(obj.dependents),
+				dep=obj.dependents{i};
+				md=checkconsistency(dep,md,solution,analyses);
+			end
+			for i=1:numel(obj.independents),
+				indep=obj.independents{i};
+				md=checkconsistency(indep,md,i,solution,analyses,obj.driver);
+			end
 
 		end % }}}
 		function disp(obj) % {{{
-			disp(sprintf('   automatic differentiation parameters:'));
+			disp(sprintf('      automatic differentiation parameters:'));
 			fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
-			fielddisplay(obj,'dependents','list of dependent variables ; ex: {''Thickness'',''FrictionCoefficient''}');
-			fielddisplay(obj,'independents','list of independent variables ; ex: {''IceVolume'',''MassFlux''}');
+			fielddisplay(obj,'dependents','list of dependent variables');
+			fielddisplay(obj,'independents','list of independent variables');
+			fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
 		end % }}}
 		function marshall(obj,fid) % {{{
 
 			WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
-			
+			WriteData(fid,'object',obj,'fieldname','driver','format','String');
+
 			%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
+			if ~obj.isautodiff,
+				WriteData(fid,'data',false,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
+				WriteData(fid,'data',false,'enum',AutodiffKeepEnum(),'format','Boolean');
+				return;
+			end
+
+			%process dependent variables {{{
+			num_dependent_objects=numel(obj.dependents);
+			WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer');
+
+			if(num_dependent_objects),
+				names=zeros(num_dependent_objects,1);
+				types=zeros(num_dependent_objects,1);
+				indices=zeros(num_dependent_objects,1);
+
+				for i=1:num_dependent_objects,
+					dep=obj.dependents{i};
+
+					names(i)=StringToEnum(dep.name);
+					types(i)=dep.typetoscalar();
+					indices(i)=dep.index;
+				end
+				WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3);
+				WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3);
+				WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3);
+			end
+			%}}}
+			%process independent variables {{{
+			num_independent_objects=numel(obj.independents);
+			WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer');
+
+			if(num_independent_objects),
+				names=zeros(num_independent_objects,1);
+				types=zeros(num_independent_objects,1);
+
+				for i=1:num_independent_objects,
+					indep=obj.independents{i};
+
+					names(i)=StringToEnum(indep.name);
+					types(i)=indep.typetoscalar();
+				end
+				WriteData(fid,'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3);
+				WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3);
+			end
+			%}}}
+			%if driver is fos_forward, build index:  {{{
+			if strcmpi(obj.driver,'fos_forward'),
+				index=0;
+
+				for i=1:num_independent_objects,
+					indep=obj.independents{i};
+					if ~isnan(indep.fos_forward_index),
+						index=index+indep.fos_forward_index;
+						break;
+					else
+						if strcmpi(indep.type,'scalar'),
+							index=index+1;
+						else
+							index=index+indep.nods;
+						end
+					end
+				end
+				index=index-1; %get c-index numbering going
+				WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer');
+			end
+			%}}}
+			%if driver is fos_reverse, build index:  {{{
+			if strcmpi(obj.driver,'fos_reverse'),
+				index=0;
+
+				for i=1:num_dependent_objects,
+					dep=obj.dependents{i};
+					if ~isnan(dep.fos_reverse_index),
+						index=index+dep.fos_reverse_index;
+						break;
+					else
+						if strcmpi(dep.type,'scalar'),
+							index=index+1;
+						else
+							index=index+dep.nods;
+						end
+					end
+				end
+				index=index-1; %get c-index numbering going
+				WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer');
+			end
+			%}}}
+			%if driver is fov_forward, build indices:  {{{
+			if strcmpi(obj.driver,'fov_forward'),
+				indices=0;
+
+				for i=1:num_independent_objects,
+					indep=obj.independents{i};
+					if ~isempty(indep.fos_forward_index),
+						indices=indices+indep.fov_forward_indices;
+						break;
+					else
+						if strcmpi(indep.type,'scalar'),
+							indices=indices+1;
+						else
+							indices=indices+indep.nods;
+						end
+					end
+				end
+				indices=indices-1; %get c-indices numbering going
+				WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3);
+			end
+			%}}}
+			%deal with mass fluxes:  {{{
+			mass_flux_segments=cell(0,1);
+			for i=1:num_dependent_objects,
+				dep=obj.dependents{i};
+				if strcmpi(dep.name,'MassFlux'),
+					mass_flux_segments{end+1,1}=dep.segments;
+				end
+			end
+			if ~isempty(mass_flux_segments), 
+				WriteData(fid,'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');
+				flag=true;
+			else
+				flag=false;
+			end
+			WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
+			%}}}
+			%deal with trace keep on: {{{
+			keep=false;
+
+			%From ADOLC userdoc: 
+			% The optional integer argument keep of trace on determines whether the numerical values of all active variables are 
+			% recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and 
+			% prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse 
+			% mode as described in the Section 4 and Section 5. 
+			%
+
+			if length(obj.driver)<=3,
+				keep=false; %there is no "_reverse" string within the driver string: 
+			else
+				if strncmpi(obj.driver(4:end),'_reverse',8),
+					keep=true;
+				else
+					keep=false;
+				end
+			end
+			WriteData(fid,'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean');
+			%}}}
 
 		end % }}}
Index: /issm/trunk/src/m/classes/autodiff.py
===================================================================
--- /issm/trunk/src/m/classes/autodiff.py	(revision 13974)
+++ /issm/trunk/src/m/classes/autodiff.py	(revision 13975)
@@ -1,3 +1,6 @@
 #module imports
+import numpy
+from dependent import *
+from independent import *
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -14,24 +17,46 @@
 
 	#properties
-	def __init__(self):
-		# {{{ Properties
-		self.isautodiff = False
+	def __init__(self,*args):    # {{{
+		self.isautodiff   = False
+		self.dependents   = []
+		self.independents = []
+		self.driver       = 'fos_forward'
 
-		#set defaults
-		self.setdefaultparameters()
+		if not len(args):
+			self.setdefaultparameters()
+		else:
+			raise RuntimeError("constructor not supported")
+	# }}}
 
-		#}}}
-	def __repr__(self):
-		# {{{ Display
-		string='   automatic differentiation parameters:'
-		string="%s\n%s"%(string,fielddisplay(self,'isautodiff','indicates if the automatic differentiation is activated'))
-		return string
-		#}}}
-	def setdefaultparameters(self):
-		# {{{setdefaultparameters
+	def __repr__(self):    # {{{
+		s ="      automatic differentiation parameters:\n"
+
+		s+="%s\n" % fielddisplay(self,'isautodiff',"indicates if the automatic differentiation is activated")
+		s+="%s\n" % fielddisplay(self,'dependents',"list of dependent variables")
+		s+="%s\n" % fielddisplay(self,'independents',"list of independent variables")
+		s+="%s\n" % fielddisplay(self,'driver',"ADOLC driver ('fos_forward' or 'fov_forward')")
+
+		return s
+	# }}}
+
+	def setdefaultparameters(self):    # {{{
 		return self
-	#}}}
+	# }}}
 
 	def checkconsistency(self,md,solution,analyses):    # {{{
+
+		#Early return 
+		if not self.isautodiff:
+			return md
+
+		#Driver value:
+		md = checkfield(md,'autodiff.driver','values',['fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'])
+
+		#go through our dependents and independents and check consistency: 
+		for dep in self.dependents:
+			dep.checkconsistency(md,solution,analyses)
+		for i,indep in enumerate(self.independents):
+			indep.checkconsistency(md,i,solution,analyses,self.driver)
+
 		return md
 	# }}}
@@ -39,4 +64,133 @@
 	def marshall(self,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
+		WriteData(fid,'object',self,'fieldname','driver','format','String')
+
+		#early return
+		if not self.isautodiff:
+			WriteData(fid,'data',False,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
+			WriteData(fid,'data',False,'enum',AutodiffKeepEnum(),'format','Boolean')
+			return
+
+		#process dependent variables {{{
+		num_dependent_objects=len(self.dependents)
+		WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer')
+
+		if num_dependent_objects:
+			names=numpy.zeros(num_dependent_objects)
+			types=numpy.zeros(num_dependent_objects)
+			indices=numpy.zeros(num_dependent_objects)
+
+			for i,dep in enumerate(self.dependents):
+				names[i]=StringToEnum(dep.name)[0]
+				types[i]=dep.typetoscalar()
+				indices[i]=dep.index
+
+			WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3)
+			WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3)
+			WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3)
+		#}}}
+
+		#process independent variables {{{
+		num_independent_objects=len(self.independents)
+		WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer')
+
+		if num_independent_objects:
+			names=numpy.zeros(num_independent_objects)
+			types=numpy.zeros(num_independent_objects)
+
+			for i,indep in enumerate(self.independents):
+				names[i]=StringToEnum(indep.name)[0]
+				types[i]=indep.typetoscalar()
+
+			WriteData(fid,'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3)
+			WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3)
+		#}}}
+
+		#if driver is fos_forward, build index:  {{{
+		if strcmpi(self.driver,'fos_forward'):
+			index=0
+
+			for indep in self.independents:
+				if not numpy.isnan(indep.fos_forward_index):
+					index+=indep.fos_forward_index
+					break
+				else:
+					if strcmpi(indep.type,'scalar'):
+						index+=1
+					else:
+						index+=indep.nods
+
+			index-=1    #get c-index numbering going
+			WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer')
+		#}}}
+
+		#if driver is fos_reverse, build index:  {{{
+		if strcmpi(self.driver,'fos_reverse'):
+			index=0
+
+			for dep in self.dependents:
+				if not numpy.isnan(dep.fos_reverse_index):
+					index+=dep.fos_reverse_index
+					break
+				else:
+					if strcmpi(dep.type,'scalar'):
+						index+=1
+					else:
+						index+=dep.nods
+
+			index-=1    #get c-index numbering going
+			WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer')
+		#}}}
+
+		#if driver is fov_forward, build indices:  {{{
+		if strcmpi(self.driver,'fov_forward'):
+			indices=0
+
+			for indep in self.independents:
+				if indep.fos_forward_index:
+					indices+=indep.fov_forward_indices
+					break
+				else:
+					if strcmpi(indep.type,'scalar'):
+						indices+=1
+					else:
+						indices+=indep.nods
+
+			indices-=1    #get c-indices numbering going
+			WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3)
+		#}}}
+
+		#deal with mass fluxes:  {{{
+		mass_flux_segments=[dep.segments for dep in self.dependents if strcmpi(dep.name,'MassFlux')]
+
+		if mass_flux_segments:
+			WriteData(fid,'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray')
+			flag=True
+		else:
+			flag=False
+		WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
+		#}}}
+
+		#deal with trace keep on: {{{
+		keep=False
+
+		#From ADOLC userdoc: 
+		# The optional integer argument keep of trace on determines whether the numerical values of all active variables are 
+		# recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and 
+		# prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse 
+		# mode as described in the Section 4 and Section 5. 
+		#
+
+		if len(self.driver)<=3:
+			keep=False    #there is no "_reverse" string within the driver string: 
+		else:
+			if strncmpi(self.driver[3:],'_reverse',8):
+				keep=True
+			else:
+				keep=False
+		WriteData(fid,'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean')
+		#}}}
+
+		return
 	# }}}
 
Index: /issm/trunk/src/m/classes/bamggeom.py
===================================================================
--- /issm/trunk/src/m/classes/bamggeom.py	(revision 13974)
+++ /issm/trunk/src/m/classes/bamggeom.py	(revision 13975)
@@ -1,2 +1,4 @@
+import numpy
+
 class bamggeom(object):
 	"""
@@ -8,12 +10,12 @@
 
 	def __init__(self,*args):    # {{{
-		self.Vertices=[]
-		self.Edges=[]
-		self.TangentAtEdges=[]
-		self.Corners=[]
-		self.RequiredVertices=[]
-		self.RequiredEdges=[]
-		self.CrackedEdges=[]
-		self.SubDomains=[]
+		self.Vertices=numpy.empty((0,3))
+		self.Edges=numpy.empty((0,3))
+		self.TangentAtEdges=numpy.empty((0,4))
+		self.Corners=numpy.empty((0,1))
+		self.RequiredVertices=numpy.empty((0,1))
+		self.RequiredEdges=numpy.empty((0,1))
+		self.CrackedEdges=numpy.empty((0,0))
+		self.SubDomains=numpy.empty((0,4))
 
 		if not len(args):
Index: /issm/trunk/src/m/classes/bamgmesh.py
===================================================================
--- /issm/trunk/src/m/classes/bamgmesh.py	(revision 13974)
+++ /issm/trunk/src/m/classes/bamgmesh.py	(revision 13975)
@@ -1,2 +1,4 @@
+import numpy
+
 class bamgmesh(object):
 	"""
@@ -8,20 +10,20 @@
 
 	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=[]
+		self.Vertices=numpy.empty((0,3))
+		self.Edges=numpy.empty((0,3))
+		self.Triangles=numpy.empty((0,0))
+		self.Quadrilaterals=numpy.empty((0,0))
+		self.IssmEdges=numpy.empty((0,0))
+		self.IssmSegments=numpy.empty((0,0))
+		self.VerticesOnGeomVertex=numpy.empty((0,0))
+		self.VerticesOnGeomEdge=numpy.empty((0,0))
+		self.EdgesOnGeomEdge=numpy.empty((0,0))
+		self.SubDomains=numpy.empty((0,4))
+		self.SubDomainsFromGeom=numpy.empty((0,0))
+		self.ElementConnectivity=numpy.empty((0,0))
+		self.NodalConnectivity=numpy.empty((0,0))
+		self.NodalElementConnectivity=numpy.empty((0,0))
+		self.CrackedVertices=numpy.empty((0,0))
+		self.CrackedEdges=numpy.empty((0,0))
 
 		if not len(args):
Index: /issm/trunk/src/m/classes/clusters/cloud.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/cloud.m	(revision 13975)
+++ /issm/trunk/src/m/classes/clusters/cloud.m	(revision 13975)
@@ -0,0 +1,89 @@
+%CLOUD cluster class definition
+%
+%   Usage:
+%      cluster=cloud('name','astrid','np',3);
+%      cluster=cloud('name',oshostname(),'np',3,'login','username');
+
+classdef cloud
+	properties (SetAccess=public) 
+		% {{{
+		name='';
+		login='';
+		np=1;
+		codepath='';
+		executionpath='';
+		interactive=0;
+		%}}}
+	end
+	methods
+		function cluster=cloud(varargin) % {{{
+
+			%initialize cluster using user settings if provided
+			if (exist('cloud_settings')==2), 
+				eval('cloud_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('    codepath: %s',cluster.codepath));
+			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    interactive: %i',cluster.interactive));
+		end
+		%}}}
+		function md = checkconsistency(cluster,md,solution,analyses) % {{{
+			if cluster.np<1
+				md = checkmessage(md,['number of processors should be at least 1']);
+			end
+			if isnan(cluster.np),
+				md = checkmessage(md,'number of processors should not be NaN!');
+			end
+		end
+		%}}}
+		function BuildQueueScript(cluster,dirname,modelname,solution,io_gather,isvalgrind,isgprof) % {{{
+
+			%write queuing script 
+			fid=fopen([modelname '.queue'],'w');
+			fprintf(fid,'#!/bin/bash\n');
+			if cluster.interactive
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname);
+			else
+				fprintf(fid,'mpiexec -np %i -f /home/mpich2.hosts %s/issm.exe %s %s %s 2> %s.errlog >%s.outlog ',cluster.np,cluster.codepath,EnumToString(solution),[cluster.executionpath '/' dirname],modelname,modelname,modelname);
+			end
+		end
+		%}}}
+		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');
+			issmstscpout(cluster.name,cluster.executionpath,cluster.login,{[dirname '.tar.gz']});
+
+			disp('launching solution sequence on remote cluster');
+			launchcommand=['cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
+			issmstssh(cluster.name,cluster.login,launchcommand);
+		end %}}}
+		function Download(cluster,dirname,filelist)% {{{
+
+			%copy files from cluster to current directory
+			directory=[cluster.executionpath '/' dirname '/'];
+			issmstscpin(cluster.name,cluster.login,directory,filelist);
+		end %}}}
+	end
+end
Index: /issm/trunk/src/m/classes/clusters/discover.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/discover.m	(revision 13974)
+++ /issm/trunk/src/m/classes/clusters/discover.m	(revision 13975)
@@ -106,5 +106,6 @@
 			 fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
 			 fprintf(fid,'. /usr/share/modules/init/bash\n\n');
-			 fprintf(fid,'module load comp/intel-10.1.023\n');
+			 fprintf(fid,'module purge\n');
+			 fprintf(fid,'module load comp/intel-11.1.038\n');
 			 fprintf(fid,'module load mpi/impi-4.0.3.008\n');
 			 fprintf(fid,'module load lib/mkl-10.1.2.024\n\n');
Index: /issm/trunk/src/m/classes/clusters/generic.m
===================================================================
--- /issm/trunk/src/m/classes/clusters/generic.m	(revision 13974)
+++ /issm/trunk/src/m/classes/clusters/generic.m	(revision 13975)
@@ -14,4 +14,5 @@
 		interactive=1;
 		codepath=[issmdir() '/bin'];
+		etcpath=[issmdir() '/etc'];
 		executionpath=[issmdir() '/execution'];
 		valgrind=[issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
@@ -45,4 +46,5 @@
 			disp(sprintf('    codepath: %s',cluster.codepath));
 			disp(sprintf('    executionpath: %s',cluster.executionpath));
+			disp(sprintf('    etcpath: %s',cluster.executionpath));
 			disp(sprintf('    valgrind: %s',cluster.valgrind));
 			disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
@@ -190,5 +192,5 @@
 
 			disp('launching solution sequence on remote cluster');
-			launchcommand=['source ' issmdir '/etc/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
+			launchcommand=['source ' cluster.etcpath '/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
 				' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
 			issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
Index: /issm/trunk/src/m/classes/dependent.m
===================================================================
--- /issm/trunk/src/m/classes/dependent.m	(revision 13975)
+++ /issm/trunk/src/m/classes/dependent.m	(revision 13975)
@@ -0,0 +1,87 @@
+%DEPENDENT class definition
+%
+%   Usage:
+%      dependent=dependent();
+
+classdef dependent
+	properties (SetAccess=public) 
+		name                 = '';
+		type                 = '';
+		fos_reverse_index    = NaN;
+		exp                  = '';
+		segments             = [];
+		index                = -1;
+		nods                 = 0;
+	end
+	methods
+		function obj = dependent(varargin) % {{{
+
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
+
+			obj.name=getfieldvalue(options,'name','');
+			obj.type=getfieldvalue(options,'type','');
+			obj.exp=getfieldvalue(options,'exp','');
+			obj.segments=getfieldvalue(options,'segments',[]);
+			obj.index=getfieldvalue(options,'index',-1);
+			obj.nods=getfieldvalue(options,'nods',0);
+
+			%if name is mass flux: 
+			if strcmpi(obj.name,'MassFlux'),
+				%make sure that we supplied a file and that it exists! 
+				if exist(obj.exp)~=2,
+					error('dependent checkconsistency: specified ''exp'' file does not exist!');
+				end
+				%process the file and retrieve segments
+				mesh=getfieldvalue(options,'mesh');
+				obj.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,obj.exp);
+			end
+		end
+		%}}}
+		function obj = setdefaultparameters(obj) % {{{
+			%do nothing
+		end % }}}
+		function md = checkconsistency(obj,md,solution,analyses) % {{{
+			if strcmpi(obj.name,'MassFlux'),
+				if isempty(obj.segments),
+					error('dependent checkconsistency error: need segments to compute this dependent response');
+				end
+				if obj.index<=0,
+					error('dependent checkconsistency error: index for segments should be >=1');
+				end
+			end
+			if ~isnan(obj.fos_reverse_index),
+				if ~strcmpi(driver,'fos_reverse'),
+					error('cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!');
+				end
+				if obj.nods==0,
+					error('dependent checkconsistency error: nods should be set to the size of the independent variable');
+				end
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   dependent variable:'));
+
+			fielddisplay(obj,'name','variable name (must match corresponding Enum)');
+			fielddisplay(obj,'type','type of variable (''vertex'' or ''scalar'')');
+
+			if ~isnan(obj.fos_reverse_index),
+				fielddisplay(obj,'fos_reverse_index','index for fos_reverse driver of ADOLC');
+			end
+			if ~isempty(obj.exp),
+				fielddisplay(obj,'exp','file needed to compute dependent variable');
+				fielddisplay(obj,'segments','mass flux segments');
+			end
+
+		end % }}}
+		function scalar=typetoscalar(obj) % {{{
+			if strcmpi(obj.type,'scalar'),
+				scalar=0;
+			elseif strcmpi(obj.type,'vertex'),
+				scalar=1;
+			end
+
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/dependent.py
===================================================================
--- /issm/trunk/src/m/classes/dependent.py	(revision 13975)
+++ /issm/trunk/src/m/classes/dependent.py	(revision 13975)
@@ -0,0 +1,94 @@
+import os.path
+import numpy
+from pairoptions import *
+from fielddisplay import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from WriteData import *
+from MeshProfileIntersection import *
+
+class dependent(object):
+	"""
+	DEPENDENT class definition
+
+	   Usage:
+	      dependent=dependent();
+	"""
+
+	def __init__(self,*args):    # {{{
+		self.name                 = ''
+		self.type                 = ''
+		self.fos_reverse_index    = float('NaN')
+		self.exp                  = ''
+		self.segments             = []
+		self.index                = -1
+		self.nods                 = 0
+
+		#set defaults 
+		self.setdefaultparameters()
+
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		self.name=options.getfieldvalue('name','')
+		self.type=options.getfieldvalue('type','')
+		self.exp=options.getfieldvalue('exp','')
+		self.segments=options.getfieldvalue('segments',[])
+		self.index=options.getfieldvalue('index',-1)
+		self.nods=options.getfieldvalue('nods',0)
+
+		#if name is mass flux: 
+		if strcmpi(self.name,'MassFlux'):
+			#make sure that we supplied a file and that it exists! 
+			if not os.path.exists(self.exp):
+				raise IOError("dependent checkconsistency: specified 'exp' file does not exist!")
+			#process the file and retrieve segments
+			mesh=options.getfieldvalue('mesh')
+			self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp)
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="   dependent variable:\n"
+
+		s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")
+		s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')")
+
+		if not numpy.isnan(self.fos_reverse_index):
+			s+="%s\n" % fielddisplay(self,'fos_reverse_index',"index for fos_reverse driver of ADOLC")
+		if self.exp:
+			s+="%s\n" % fielddisplay(self,'exp',"file needed to compute dependent variable")
+			s+="%s\n" % fielddisplay(self,'segments',"mass flux segments")
+
+		return s
+	# }}}
+
+	def setdefaultparameters(self):    # {{{
+		#do nothing
+		return self
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		if strcmpi(self.name,'MassFlux'):
+			if not self.segments:
+				raise RuntimeError("dependent checkconsistency error: need segments to compute this dependent response")
+			if self.index<0:
+				raise RuntimeError("dependent checkconsistency error: index for segments should be >=0")
+
+		if not numpy.isnan(self.fos_reverse_index):
+			if not strcmpi(driver,'fos_reverse'):
+				raise TypeError("cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!")
+			if self.nods==0:
+				raise TypeError("dependent checkconsistency error: nods should be set to the size of the independent variable")
+
+		return md
+	# }}}
+
+	def typetoscalar(self):    # {{{
+		if   strcmpi(self.type,'scalar'):
+			scalar=0
+		elif strcmpi(self.type,'vertex'):
+			scalar=1
+
+		return scalar
+	# }}}
+
Index: /issm/trunk/src/m/classes/diagnostic.m
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.m	(revision 13974)
+++ /issm/trunk/src/m/classes/diagnostic.m	(revision 13975)
@@ -38,10 +38,10 @@
 			 %maximum of non-linear iterations.
 			 obj.maxiter=100;
-			 
+
 			 %Convergence criterion: absolute, relative and residual
 			 obj.restol=10^-4; 
 			 obj.reltol=0.01;
 			 obj.abstol=10;
-			 
+
 			 obj.stokesreconditioning=10^13;
 			 obj.shelf_dampening=0;
@@ -92,5 +92,5 @@
 
 			%singular solution
-			if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
+			if ~(any(~isnan(md.diagnostic.spcvx)) & any(~isnan(md.diagnostic.spcvy))),
 				md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
 			end
Index: /issm/trunk/src/m/classes/diagnostic.py
===================================================================
--- /issm/trunk/src/m/classes/diagnostic.py	(revision 13974)
+++ /issm/trunk/src/m/classes/diagnostic.py	(revision 13975)
@@ -2,4 +2,5 @@
 import numpy
 import sys
+import copy
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -186,5 +187,5 @@
 
 		#marshall ice front
-		data=self.icefront
+		data=copy.deepcopy(self.icefront)
 		data[numpy.nonzero(data[:,-1]==0),-1]=AirEnum()
 		data[numpy.nonzero(data[:,-1]==1),-1]=WaterEnum()
Index: /issm/trunk/src/m/classes/flaim.m
===================================================================
--- /issm/trunk/src/m/classes/flaim.m	(revision 13974)
+++ /issm/trunk/src/m/classes/flaim.m	(revision 13975)
@@ -59,5 +59,5 @@
 			fielddisplay(obj,'usevalueordering'   ,'flag to consider target values for flight path evaluation');
 			fielddisplay(obj,'split_antimeridian' ,'flag to split polygons on the antimeridian');
-			
+
 			disp(sprintf('\n      Optimization:'));
 			fielddisplay(obj,'path_optimize'     ,'optimize? (default false)');
Index: /issm/trunk/src/m/classes/flowequation.py
===================================================================
--- /issm/trunk/src/m/classes/flowequation.py	(revision 13974)
+++ /issm/trunk/src/m/classes/flowequation.py	(revision 13975)
@@ -1,4 +1,5 @@
 #module imports
 import numpy
+import copy
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -67,6 +68,6 @@
 				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))
+				md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,7+1))
+				md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,7+1))
 			if not (self.ismacayealpattyn or self.ishutter or self.isstokes or self.isl1l2):
 				md.checkmessage("no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1")
@@ -89,5 +90,5 @@
 		WriteData(fid,'object',self,'fieldname','borderstokes','format','DoubleMat','mattype',1)
 		#convert approximations to enums
-		data=self.vertex_equation
+		data=copy.deepcopy(self.vertex_equation)
 		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
 		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
@@ -100,5 +101,5 @@
 		data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
 		WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
-		data=self.element_equation
+		data=copy.deepcopy(self.element_equation)
 		data[numpy.nonzero(data==0)]=NoneApproximationEnum()
 		data[numpy.nonzero(data==1)]=HutterApproximationEnum()
Index: /issm/trunk/src/m/classes/groundingline.m
===================================================================
--- /issm/trunk/src/m/classes/groundingline.m	(revision 13974)
+++ /issm/trunk/src/m/classes/groundingline.m	(revision 13975)
@@ -25,5 +25,4 @@
 			%basal melting rate correction: 
 			obj.melting_rate=0; 
-
 
 		end % }}}
Index: /issm/trunk/src/m/classes/independent.m
===================================================================
--- /issm/trunk/src/m/classes/independent.m	(revision 13975)
+++ /issm/trunk/src/m/classes/independent.m	(revision 13975)
@@ -0,0 +1,70 @@
+%INDEPENDENT class definition
+%
+%   Usage:
+%      independent=independent();
+
+classdef independent
+	properties (SetAccess=public) 
+		name                 = '';
+		type                 = '';
+		fos_forward_index    = NaN;
+		fov_forward_indices  = [];
+		nods                 = 0;
+	end
+	methods
+		function obj = independent(varargin) % {{{
+
+			%use provided options to change fields
+			options=pairoptions(varargin{:});
+
+			%OK get other fields
+			obj=AssignObjectFields(pairoptions(varargin{:}),obj);
+
+		end
+		%}}}
+		function obj = setdefaultparameters(obj) % {{{
+			%do nothing
+
+		end % }}}
+		function md = checkconsistency(obj,md,i,solution,analyses,driver) % {{{
+			if ~isnan(obj.fos_forward_index),
+				if ~strcmpi(driver,'fos_forward'),
+					error('cannot declare an independent with a fos_forward_index when the driver is not fos_forward!');
+				end
+				if obj.nods==0,
+					error('independent checkconsistency error: nods should be set to the size of the independent variable');
+				end
+			end
+
+			if ~isempty(obj.fov_forward_indices),
+				if ~strcmpi(driver,'fov_forward'),
+					error('cannot declare an independent with fov_forward_indices when the driver is not fov_forward!');
+				end
+				if obj.nods==0,
+					error('independent checkconsistency error: nods should be set to the size of the independent variable');
+				end
+				md = checkfield(md,['autodiff.independents{' num2str(i) '}.fov_forward_indices'],'>=',1,'<=',obj.nods,'size',[NaN 1]);
+			end
+
+		end % }}}
+		function disp(obj) % {{{
+			disp(sprintf('   independent variable:'));
+
+			fielddisplay(obj,'name','variable name (must match corresponding Enum)');
+			fielddisplay(obj,'type','type of variable (''vertex'' or ''scalar'')');
+			if ~isnan(obj.fos_forward_index),
+				fielddisplay(obj,'fos_forward_index','index for fos_foward driver of ADOLC');
+			end
+			if ~isnan(obj.fov_forward_indices),
+				fielddisplay(obj,'fov_forward_indices','indices for fov_foward driver of ADOLC');
+			end
+		end % }}}
+		function scalar=typetoscalar(obj) % {{{
+			if strcmpi(obj.type,'scalar'),
+				scalar=0;
+			elseif strcmpi(obj.type,'vertex'),
+				scalar=1;
+			end
+		end % }}}
+	end
+end
Index: /issm/trunk/src/m/classes/independent.py
===================================================================
--- /issm/trunk/src/m/classes/independent.py	(revision 13975)
+++ /issm/trunk/src/m/classes/independent.py	(revision 13975)
@@ -0,0 +1,76 @@
+import numpy
+from pairoptions import *
+from fielddisplay import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from WriteData import *
+
+class independent(object):
+	"""
+	INDEPENDENT class definition
+
+	   Usage:
+	      independent=independent();
+	"""
+
+	def __init__(self,*args):    # {{{
+		self.name                 = ''
+		self.type                 = ''
+		self.fos_forward_index    = float('NaN')
+		self.fov_forward_indices  = numpy.array([])
+		self.nods                 = 0
+
+		#set defaults
+		self.setdefaultparameters()
+
+		#use provided options to change fields
+		options=pairoptions(*args)
+
+		#OK get other fields
+		self=options.AssignObjectFields(self)
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="   independent variable:\n"
+
+		s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")
+		s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')")
+		if not numpy.isnan(self.fos_forward_index):
+			s+="%s\n" % fielddisplay(self,'fos_forward_index',"index for fos_foward driver of ADOLC")
+		if numpy.any(numpy.logical_not(numpy.isnan(self.fov_forward_indices))):
+			s+="%s\n" % fielddisplay(self,'fov_forward_indices',"indices for fov_foward driver of ADOLC")
+
+		return s
+	# }}}
+
+	def setdefaultparameters(self):    # {{{
+		#do nothing
+		return self
+	# }}}
+
+	def checkconsistency(self,md,i,solution,analyses,driver):    # {{{
+		if not numpy.isnan(self.fos_forward_index):
+			if not strcmpi(driver,'fos_forward'):
+				raise TypeError("cannot declare an independent with a fos_forward_index when the driver is not fos_forward!")
+			if self.nods==0:
+				raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable")
+
+		if self.fov_forward_indices:
+			if not strcmpi(driver,'fov_forward'):
+				raise TypeError("cannot declare an independent with fov_forward_indices when the driver is not fov_forward!")
+			if self.nods==0:
+				raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable")
+			md = checkfield(md,"autodiff.independents[%d].fov_forward_indices" % i,'>=',1,'<=',self.nods,'size',[float('NaN'),1])
+
+		return md
+	# }}}
+
+	def typetoscalar(self):    # {{{
+		if   strcmpi(self.type,'scalar'):
+			scalar=0
+		elif strcmpi(self.type,'vertex'):
+			scalar=1
+
+		return scalar
+	# }}}
+
Index: /issm/trunk/src/m/classes/initialization.py
===================================================================
--- /issm/trunk/src/m/classes/initialization.py	(revision 13974)
+++ /issm/trunk/src/m/classes/initialization.py	(revision 13975)
@@ -24,4 +24,6 @@
 		self.pressure      = float('NaN')
 		self.temperature   = float('NaN')
+		self.surfacetemp   = float('NaN')
+		self.basaltemp     = float('NaN')
 		self.watercolumn   = float('NaN')
 		self.waterfraction = float('NaN')
@@ -41,4 +43,6 @@
 		string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure field'))
 		string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature in Kelvins'))
+		string="%s\n%s"%(string,fielddisplay(self,'surfacetemp','surface temperature in Kelvins'))
+		string="%s\n%s"%(string,fielddisplay(self,'basaltemp','basal temperature in Kelvins'))
 		string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water'))
 		string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
@@ -86,4 +90,6 @@
 		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.surfacetemp,'format','DoubleMat','mattype',1,'enum',TemperatureSurfaceEnum()) 
+		WriteData(fid,'data',self.basaltemp,'format','DoubleMat','mattype',1,'enum',TemperatureBasalEnum())
 		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.py
===================================================================
--- /issm/trunk/src/m/classes/inversion.py	(revision 13974)
+++ /issm/trunk/src/m/classes/inversion.py	(revision 13975)
@@ -1,4 +1,5 @@
 #module imports
 import numpy
+import copy
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -96,8 +97,8 @@
 		#inversed parameter (10^8 for B, 50 for drag) and can be decreased
 		#after the first iterations
-		self.gradient_scaling=50*numpy.ones(self.nsteps)
+		self.gradient_scaling=50*numpy.ones((self.nsteps,1))
 
 		#several responses can be used:
-		self.cost_functions=101*numpy.ones(self.nsteps)
+		self.cost_functions=101*numpy.ones((self.nsteps,1))
 
 		#step_threshold is used to speed up control method. When
@@ -124,10 +125,10 @@
 
 		num_controls=numpy.size(md.inversion.control_parameters)
-		num_costfunc=numpy.size(md.inversion.cost_functions,1)
+		num_costfunc=numpy.size(md.inversion.cost_functions,axis=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.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],'>=',0)
@@ -171,12 +172,12 @@
 
 		#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)]
+		num_control_parameters=len(self.control_parameters)
+		data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1)
 		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
+		num_cost_functions=numpy.size(self.cost_functions,axis=1)
+		data=copy.deepcopy(self.cost_functions)
 		data[numpy.nonzero(data==101)]=SurfaceAbsVelMisfitEnum()
 		data[numpy.nonzero(data==102)]=SurfaceRelVelMisfitEnum()
Index: /issm/trunk/src/m/classes/matdamageice.py
===================================================================
--- /issm/trunk/src/m/classes/matdamageice.py	(revision 13975)
+++ /issm/trunk/src/m/classes/matdamageice.py	(revision 13975)
@@ -0,0 +1,133 @@
+#module imports
+from fielddisplay import fielddisplay
+from EnumDefinitions import *
+from StringToEnum import StringToEnum
+from checkfield import *
+from WriteData import *
+
+class matdamageice(object):
+	"""
+	MATDAMAGEICE class definition
+
+	   Usage:
+	      matdamageice=matdamageice();
+	"""
+
+	def __init__(self,*args):    # {{{
+		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_Z   = float('NaN')
+		self.rheology_law = ''
+
+		if not len(args):
+			self.setdefaultparameters()
+		else:
+			raise RuntimeError("constructor not supported")
+
+	# }}}
+
+	def setdefaultparameters(self):    # {{{
+
+		#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'
+	# }}}
+
+	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,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'])
+
+		return md
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ='   Materials:\n'
+
+		s+="%s\n" % fielddisplay(self,"rho_ice","ice density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"rho_water","ocean water density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"rho_freshwater","fresh water density [kg/m^3]")
+		s+="%s\n" % fielddisplay(self,"mu_water","water viscosity [N s/m^2]")
+		s+="%s\n" % fielddisplay(self,"heatcapacity","heat capacity [J/kg/K]")
+		s+="%s\n" % fielddisplay(self,"thermalconductivity","ice thermal conductivity [W/m/K]")
+		s+="%s\n" % fielddisplay(self,"meltingpoint","melting point of ice at 1atm in K")
+		s+="%s\n" % fielddisplay(self,"latentheat","latent heat of fusion [J/m^3]")
+		s+="%s\n" % fielddisplay(self,"beta","rate of change of melting point with pressure [K/Pa]")
+		s+="%s\n" % fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]")
+		s+="%s\n" % fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]")
+		s+="%s\n" % fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]")
+		s+="%s\n" % fielddisplay(self,"rheology_n","Glen's flow law exponent")
+		s+="%s\n" % fielddisplay(self,"rheology_Z","rheology multiplier")
+		s+="%s\n" % fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Paterson' or 'Arrhenius'")
+
+		return s
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'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,'object',self,'class','materials','fieldname','rheology_Z','format','DoubleMat','mattype',1)
+		WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
+	# }}}
+
Index: /issm/trunk/src/m/classes/matice.py
===================================================================
--- /issm/trunk/src/m/classes/matice.py	(revision 13974)
+++ /issm/trunk/src/m/classes/matice.py	(revision 13975)
@@ -8,5 +8,5 @@
 class matice(object):
 	"""
-	MATERIALS class definition
+	MATICE class definition
 
 	   Usage:
Index: /issm/trunk/src/m/classes/mesh.m
===================================================================
--- /issm/trunk/src/m/classes/mesh.m	(revision 13974)
+++ /issm/trunk/src/m/classes/mesh.m	(revision 13975)
@@ -15,5 +15,5 @@
 		numberofvertices            = 0;
 		numberofedges               = 0;
-		
+
 		lat                         = NaN
 		long                        = NaN
@@ -158,5 +158,5 @@
 			fielddisplay(obj,'lowerelements','lower element list (NaN for element on the lower layer');
 			fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
-			
+
 			fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
 			fielddisplay(obj,'segmentmarkers','number associated to each segment');
Index: /issm/trunk/src/m/classes/mesh.py
===================================================================
--- /issm/trunk/src/m/classes/mesh.py	(revision 13974)
+++ /issm/trunk/src/m/classes/mesh.py	(revision 13975)
@@ -132,10 +132,10 @@
 		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))
+		md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',numpy.arange(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))):
+		if numpy.any(numpy.logical_not(ismember(numpy.arange(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])
Index: /issm/trunk/src/m/classes/model/model.m
===================================================================
--- /issm/trunk/src/m/classes/model/model.m	(revision 13974)
+++ /issm/trunk/src/m/classes/model/model.m	(revision 13975)
@@ -5,1119 +5,1119 @@
 
 classdef model
-    properties (SetAccess=public) %Model fields
-		 % {{{
-		 %Careful here: no other class should be used as default value this is a bug of matlab
-		 mesh             = 0;
-		 mask             = 0;
-
-		 geometry         = 0;
-		 constants        = 0;
-		 surfaceforcings  = 0;
-		 basalforcings    = 0;
-		 materials        = 0;
-		 friction         = 0;
-		 flowequation     = 0;
-		 timestepping     = 0;
-		 initialization   = 0;
-		 rifts            = 0;
-
-		 debug            = 0;
-		 verbose          = 0;
-		 settings         = 0;
-		 solver           = 0;
-		 cluster          = 0;
-
-		 balancethickness = 0;
-		 diagnostic       = 0;
-		 groundingline    = 0;
-		 hydrology        = 0;
-		 prognostic       = 0;
-		 thermal          = 0;
-		 steadystate      = 0;
-		 transient        = 0;
-
-		 autodiff         = 0;
-		 flaim            = 0;
-		 inversion        = 0;
-		 qmu              = 0;
-
-		 results          = 0;
-		 radaroverlay     = 0;
-		 miscellaneous    = 0;
-		 private          = 0;
-
-		 %}}}
-	 end
-	 methods (Static)
-		 function md = loadobj(md) % {{{
-			 % This function is directly called by matlab when a model object is
-			 % loaded. If the input is a struct it is an old version of model and
-			 % old fields must be recovered (make sure they are in the deprecated
-			 % model properties)
-
-			 if verLessThan('matlab','7.9'),
-				 disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
-				 disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
-
-				 % This is a Matlab bug: all the fields of md have their default value
-				 % Example of error message:
-				 % Warning: Error loading an object of class 'model':
-				 % Undefined function or method 'exist' for input arguments of type 'cell'
-				 %
-				 % This has been fixed in MATLAB 7.9 (R2009b) and later versions
-			 end
-
-			 if isstruct(md)
-				 disp('Recovering model object from a previous version');
-				 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
-	 methods
-		 function md = model(varargin) % {{{
-
-			 switch nargin
-				 case 0
-					 md=setdefaultparameters(md);
-				 otherwise
-					 error('model constructor error message: 0 of 1 argument only in input.');
-				 end
-		 end
-		 %}}}
-		 function md = checkmessage(md,string) % {{{
-			 if(nargout~=1) error('wrong usage, model must be an output'); end
-			 disp(['model not consistent: ' string]);
-			 md.private.isconsistent=false;
-		 end
-		 %}}}
-		 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
+	properties (SetAccess=public) %Model fields
+		% {{{
+		%Careful here: no other class should be used as default value this is a bug of matlab
+		mesh             = 0;
+		mask             = 0;
+
+		geometry         = 0;
+		constants        = 0;
+		surfaceforcings  = 0;
+		basalforcings    = 0;
+		materials        = 0;
+		friction         = 0;
+		flowequation     = 0;
+		timestepping     = 0;
+		initialization   = 0;
+		rifts            = 0;
+
+		debug            = 0;
+		verbose          = 0;
+		settings         = 0;
+		solver           = 0;
+		cluster          = 0;
+
+		balancethickness = 0;
+		diagnostic       = 0;
+		groundingline    = 0;
+		hydrology        = 0;
+		prognostic       = 0;
+		thermal          = 0;
+		steadystate      = 0;
+		transient        = 0;
+
+		autodiff         = 0;
+		flaim            = 0;
+		inversion        = 0;
+		qmu              = 0;
+
+		results          = 0;
+		radaroverlay     = 0;
+		miscellaneous    = 0;
+		private          = 0;
+
+		%}}}
+	end
+	methods (Static)
+		function md = loadobj(md) % {{{
+			% This function is directly called by matlab when a model object is
+			% loaded. If the input is a struct it is an old version of model and
+			% old fields must be recovered (make sure they are in the deprecated
+			% model properties)
+
+			if verLessThan('matlab','7.9'),
+				disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
+				disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
+
+				% This is a Matlab bug: all the fields of md have their default value
+				% Example of error message:
+				% Warning: Error loading an object of class 'model':
+				% Undefined function or method 'exist' for input arguments of type 'cell'
+				%
+				% This has been fixed in MATLAB 7.9 (R2009b) and later versions
+			end
+
+			if isstruct(md)
+				disp('Recovering model object from a previous version');
+				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
+			%2012 June 28th
+			if sum(sum(isnan(md.mesh.edges)))>0
+				disp('Update model edges from previous version');
+				md.mesh.edges(isnan(md.mesh.edges))=-1;
+			end
+
+		end% }}}
+	end
+	methods
+		function md = model(varargin) % {{{
+
+			switch nargin
+				case 0
+					md=setdefaultparameters(md);
+				otherwise
+					error('model constructor error message: 0 of 1 argument only in input.');
+				end
+		end
+		%}}}
+		function md = checkmessage(md,string) % {{{
+			if(nargout~=1) error('wrong usage, model must be an output'); end
+			disp(['model not consistent: ' string]);
+			md.private.isconsistent=false;
+		end
+		%}}}
+		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
+			%
+			%   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 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 nodes 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 field 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) % {{{
-
-			 if ~isstruct(structmd) error('input model is not a structure'); end
-
-			 %loaded model is a struct, initialize output and recover all fields
-			 md = structtoobj(model,structmd);
-
-			 %Old field now classes
-			 if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
-			 if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
-
-			 %Field name change
-			 if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
-			 if isfield(structmd,'p'), md.friction.p=structmd.p; end
-			 if isfield(structmd,'q'), md.friction.q=structmd.p; end
-			 if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
-			 if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
-			 if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
-			 if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
-			 if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
-			 if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
-			 if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
-			 if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
-			 if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
-			 if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
-			 if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
-			 if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
-			 if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
-			 if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
-			 if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.solver=structmd.petscoptions; end
-			 if isfield(structmd,'g'), md.constants.g=structmd.g; end
-			 if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
-			 if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
-			 if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
-			 if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
-			 if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
-			 if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
-			 if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
-			 if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
-			 if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
-			 if isfield(structmd,'riftproperties'), %old implementation
-				 md.rifts=rifts();
-				 md.rifts.riftproperties=structmd.riftproperties; 
-				 md.rifts.riftstruct=structmd.rifts;
-				 md.rifts.riftproperties=structmd.riftinfo;
-			 end
-			 if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
-			 if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
-			 if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
-			 if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
-			 if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
-			 if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
-			 if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
-			 if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
-			 if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
-			 if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
-			 if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
-			 if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
-			 if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
-			 if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
-			 if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
-			 if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
-			 if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
-			 if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
-			 if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
-			 if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
-			 if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
-			 if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
-			 if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
-			 if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
-			 if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
-			 if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
-			 if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
-			 if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
-			 if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
-			 if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
-			 if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
-			 if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
-			 if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
-			 if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
-			 if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
-			 if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
-			 if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
-			 if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
-			 if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
-			 if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
-			 if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
-			 if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
-			 if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
-			 if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
-			 if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
-			 if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
-			 if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
-			 if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
-			 if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
-			 if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
-			 if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
-			 if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
-			 if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
-			 if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
-			 if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
-			 if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
-			 if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
-			 if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
-			 if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
-			 if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
-			 if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
-			 if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
-			 if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
-			 if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
-			 if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
-			 if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
-			 if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
-			 if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
-			 if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
-			 if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
-			 if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
-			 if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
-			 if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
-			 if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
-			 if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
-			 if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
-			 if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
-			 if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
-			 if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
-			 if isfield(structmd,'long'), md.mesh.long=structmd.long; end
-			 if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
-			 if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
-			 if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
-			 if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
-			 if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
-			 if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
-			 if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
-			 if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
-			 if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
-			 if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
-			 if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
-			 if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
-			 if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
-			 if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
-			 if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
-			 if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
-			 if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
-			 if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
-			 if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
-			 if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
-			 if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
-			 if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
-			 if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
-			 if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
-			 if isfield(structmd,'edges'), md.mesh.edges=structmd.edges; end
-			 if isfield(structmd,'y'), md.mesh.y=structmd.y; end
-			 if isfield(structmd,'x'), md.mesh.x=structmd.x; end
-			 if isfield(structmd,'z'), md.mesh.z=structmd.z; end
-			 if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
-			 if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
-			 if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
-			 if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
-			 if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
-				 
-			 %Field changes
-			 if (isfield(structmd,'type') & ischar(structmd.type)), 
-				 if strcmpi(structmd.type,'2d'), md.mesh.dimension=2; end
-				 if strcmpi(structmd.type,'3d'), md.mesh.dimension=3; end
-			 end
-			 if isnumeric(md.verbose),
-				 md.verbose=verbose;
-			 end
-			 if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
-				 front=md.diagnostic.icefront;
-				 md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
-			 end
-			 if isfield(structmd,'spcvelocity'), 
-				 md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-				 md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-				 md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-				 pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4); 
-				 pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5); 
-				 pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6); 
-			 end
-			 if isfield(structmd,'spcvx'), 
-				 md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
-				 pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos); 
-			 end
-			 if isfield(structmd,'spcvy'),
-				 md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
-				 pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
-			 end
-			 if isfield(structmd,'spcvz'),
-				 md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
-				 pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
-			 end
-			 if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
-				 pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
-				 pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
-				 pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
-			 end
-			 if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
-				 pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
-				 pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
-				 pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
-				 pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
-				 pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
-				 pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
-				 pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
-				 pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
-			 end
-			 if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
-				 pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
-				 pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
-				 pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
-				 pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
-				 pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
-				 pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
-				 pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
-				 pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
-			 end
-			 if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
-				 if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
-				 if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
-				 if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
-			 end
-			 if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
-				 if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
-				 if (structmd.groundingline_migration==273), md.groundingline.migration='AgressiveMigration';  end
-				 if (structmd.groundingline_migration==274), md.groundingline.migration='SoftMigration'; end
-			 end
-			 if isfield(structmd,'control_type') & isnumeric(structmd.control_type),
-				 if (structmd.control_type==143), md.inversion.control_parameters={'FrictionCoefficient'}; end
-				 if (structmd.control_type==190), md.inversion.control_parameters={'RheologyBbar'}; end
-				 if (structmd.control_type==147), md.inversion.control_parameters={'Thickeningrate'}; end
-			 end
-			 if isfield(structmd,'cm_responses') & ismember(structmd.cm_responses(end,end),[165:170 383 388 389]),
-				 pos=find(structmd.cm_responses==166); md.inversion.cost_functions(pos)=101;
-				 pos=find(structmd.cm_responses==167); md.inversion.cost_functions(pos)=102;
-				 pos=find(structmd.cm_responses==168); md.inversion.cost_functions(pos)=103;
-				 pos=find(structmd.cm_responses==169); md.inversion.cost_functions(pos)=104;
-				 pos=find(structmd.cm_responses==170); md.inversion.cost_functions(pos)=105;
-				 pos=find(structmd.cm_responses==165); md.inversion.cost_functions(pos)=201;
-				 pos=find(structmd.cm_responses==389); md.inversion.cost_functions(pos)=501;
-				 pos=find(structmd.cm_responses==388); md.inversion.cost_functions(pos)=502;
-				 pos=find(structmd.cm_responses==382); md.inversion.cost_functions(pos)=503;
-			 end
-
-			 if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
-					 md.thermal.stabilization=2;
-					 md.prognostic.stabilization=1;
-					 md.balancethickness.stabilization=1;
-			 end
-			 if isnumeric(md.prognostic.hydrostatic_adjustment)
-				 if md.prognostic.hydrostatic_adjustment==269,
-					 md.prognostic.hydrostatic_adjustment='Incremental';
-				 else
-					 md.prognostic.hydrostatic_adjustment='Absolute';
-				 end
-			 end
-
-			 %New fields
-			 if ~isfield(structmd,'upperelements');
-				 md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
-				 md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
-			 end
-			 if ~isfield(structmd,'lowerelements');
-				 md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
-				 md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
-			 end
-				 
-			 if ~isfield(structmd,'diagnostic_ref');
-				 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-			 end
-
-		 end% }}}
-		 function md = setdefaultparameters(md) % {{{
-
-			 %initialize subclasses
-			 md.mesh             = mesh();
-			 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        = matice();
-			 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
-		 %}}}
-		 function disp(obj) % {{{
-			 disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
-			 disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
-			 disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
-			 disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
-			 disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
-			 disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
-			 disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
-			 disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
-			 disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
-			 disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
-			 disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
-			 disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
-			 disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
-			 disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
-			 disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
-			 disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
-			 disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
-			 disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
-			 disp(sprintf('%19s: %-22s -- %s','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic solution'));
-			 disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
-			 disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
-			 disp(sprintf('%19s: %-22s -- %s','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic solution'));
-			 disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
-			 disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
-			 disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
-			 disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
-			 disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
-			 disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
-			 disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
-			 disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
-			 disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
-			 disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
-		 end % }}}
-	 end
+		function md = structtomodel(md,structmd) % {{{
+
+			if ~isstruct(structmd) error('input model is not a structure'); end
+
+			%loaded model is a struct, initialize output and recover all fields
+			md = structtoobj(model,structmd);
+
+			%Old field now classes
+			if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
+			if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
+
+			%Field name change
+			if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			if isfield(structmd,'p'), md.friction.p=structmd.p; end
+			if isfield(structmd,'q'), md.friction.q=structmd.p; end
+			if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
+			if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
+			if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
+			if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
+			if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
+			if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
+			if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
+			if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
+			if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
+			if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
+			if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
+			if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
+			if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
+			if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
+			if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.solver=structmd.petscoptions; end
+			if isfield(structmd,'g'), md.constants.g=structmd.g; end
+			if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
+			if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
+			if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
+			if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
+			if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
+			if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
+			if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
+			if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
+			if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
+			if isfield(structmd,'riftproperties'), %old implementation
+				md.rifts=rifts();
+				md.rifts.riftproperties=structmd.riftproperties; 
+				md.rifts.riftstruct=structmd.rifts;
+				md.rifts.riftproperties=structmd.riftinfo;
+			end
+			if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
+			if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
+			if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
+			if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
+			if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
+			if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
+			if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
+			if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
+			if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
+			if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
+			if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
+			if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
+			if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
+			if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
+			if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
+			if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
+			if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
+			if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
+			if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
+			if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
+			if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
+			if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
+			if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
+			if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
+			if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
+			if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
+			if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
+			if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
+			if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
+			if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
+			if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
+			if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
+			if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
+			if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
+			if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
+			if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
+			if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
+			if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
+			if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
+			if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
+			if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
+			if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
+			if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
+			if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
+			if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
+			if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
+			if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
+			if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
+			if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
+			if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
+			if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
+			if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
+			if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
+			if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
+			if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
+			if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
+			if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
+			if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
+			if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
+			if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
+			if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
+			if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
+			if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
+			if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
+			if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
+			if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
+			if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
+			if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
+			if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
+			if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
+			if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
+			if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
+			if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
+			if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
+			if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
+			if isfield(structmd,'long'), md.mesh.long=structmd.long; end
+			if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
+			if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
+			if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
+			if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
+			if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
+			if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
+			if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
+			if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
+			if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
+			if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
+			if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
+			if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
+			if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
+			if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
+			if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
+			if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
+			if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
+			if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
+			if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
+			if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
+			if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
+			if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
+			if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
+			if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
+			if isfield(structmd,'edges'), 
+				md.mesh.edges=structmd.edges; 
+				md.mesh.edges(isnan(md.mesh.edges))=-1;
+			end
+			if isfield(structmd,'y'), md.mesh.y=structmd.y; end
+			if isfield(structmd,'x'), md.mesh.x=structmd.x; end
+			if isfield(structmd,'z'), md.mesh.z=structmd.z; end
+			if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
+			if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
+			if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
+			if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
+			if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
+
+			%Field changes
+			if (isfield(structmd,'type') & ischar(structmd.type)), 
+				if strcmpi(structmd.type,'2d'), md.mesh.dimension=2; end
+				if strcmpi(structmd.type,'3d'), md.mesh.dimension=3; end
+			end
+			if isnumeric(md.verbose),
+				md.verbose=verbose;
+			end
+			if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
+				front=md.diagnostic.icefront;
+				md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
+			end
+			if isfield(structmd,'spcvelocity'), 
+				md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4); 
+				pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5); 
+				pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6); 
+			end
+			if isfield(structmd,'spcvx'), 
+				md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos); 
+			end
+			if isfield(structmd,'spcvy'),
+				md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
+			end
+			if isfield(structmd,'spcvz'),
+				md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
+				pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
+			end
+			if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
+				pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
+				pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
+				pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
+			end
+			if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
+				pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
+				pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
+				pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
+				pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
+				pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
+				pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
+				pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
+				pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
+			end
+			if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
+				pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
+				pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
+				pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
+				pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
+				pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
+				pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
+				pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
+				pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
+			end
+			if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
+				if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
+				if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
+				if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
+			end
+			if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
+				if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
+				if (structmd.groundingline_migration==273), md.groundingline.migration='AgressiveMigration';  end
+				if (structmd.groundingline_migration==274), md.groundingline.migration='SoftMigration'; end
+			end
+			if isfield(structmd,'control_type') & isnumeric(structmd.control_type),
+				if (structmd.control_type==143), md.inversion.control_parameters={'FrictionCoefficient'}; end
+				if (structmd.control_type==190), md.inversion.control_parameters={'RheologyBbar'}; end
+				if (structmd.control_type==147), md.inversion.control_parameters={'Thickeningrate'}; end
+			end
+			if isfield(structmd,'cm_responses') & ismember(structmd.cm_responses(end,end),[165:170 383 388 389]),
+				pos=find(structmd.cm_responses==166); md.inversion.cost_functions(pos)=101;
+				pos=find(structmd.cm_responses==167); md.inversion.cost_functions(pos)=102;
+				pos=find(structmd.cm_responses==168); md.inversion.cost_functions(pos)=103;
+				pos=find(structmd.cm_responses==169); md.inversion.cost_functions(pos)=104;
+				pos=find(structmd.cm_responses==170); md.inversion.cost_functions(pos)=105;
+				pos=find(structmd.cm_responses==165); md.inversion.cost_functions(pos)=201;
+				pos=find(structmd.cm_responses==389); md.inversion.cost_functions(pos)=501;
+				pos=find(structmd.cm_responses==388); md.inversion.cost_functions(pos)=502;
+				pos=find(structmd.cm_responses==382); md.inversion.cost_functions(pos)=503;
+			end
+
+			if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
+					md.thermal.stabilization=2;
+					md.prognostic.stabilization=1;
+					md.balancethickness.stabilization=1;
+			end
+			if isnumeric(md.prognostic.hydrostatic_adjustment)
+				if md.prognostic.hydrostatic_adjustment==269,
+					md.prognostic.hydrostatic_adjustment='Incremental';
+				else
+					md.prognostic.hydrostatic_adjustment='Absolute';
+				end
+			end
+
+			%New fields
+			if ~isfield(structmd,'upperelements');
+				md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
+				md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
+			end
+			if ~isfield(structmd,'lowerelements');
+				md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
+				md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
+			end
+
+			if ~isfield(structmd,'diagnostic_ref');
+				md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
+			end
+
+		end% }}}
+		function md = setdefaultparameters(md) % {{{
+
+			%initialize subclasses
+			md.mesh             = mesh();
+			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        = matice();
+			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
+		%}}}
+		function disp(obj) % {{{
+			disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
+			disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
+			disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
+			disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
+			disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
+			disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
+			disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
+			disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
+			disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
+			disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
+			disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
+			disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
+			disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
+			disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
+			disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
+			disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
+			disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
+			disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
+			disp(sprintf('%19s: %-22s -- %s','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic solution'));
+			disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
+			disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
+			disp(sprintf('%19s: %-22s -- %s','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic solution'));
+			disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
+			disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
+			disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
+			disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
+			disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
+			disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
+			disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
+			disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
+			disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
+			disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
+		end % }}}
+	end
  end
Index: /issm/trunk/src/m/classes/model/model.py
===================================================================
--- /issm/trunk/src/m/classes/model/model.py	(revision 13974)
+++ /issm/trunk/src/m/classes/model/model.py	(revision 13975)
@@ -1,4 +1,5 @@
 #module imports {{{
 import numpy
+import copy
 from mesh import mesh
 from mask import mask
@@ -30,8 +31,8 @@
 from inversion import inversion
 from qmu import qmu
+from results import results
 from radaroverlay import radaroverlay
 from miscellaneous import miscellaneous
 from private import private
-from collections import OrderedDict
 from EnumDefinitions import *
 from ismumps import *
@@ -39,4 +40,8 @@
 from iluasmoptions import *
 from project3d import *
+from FlagElements import *
+from NodeConnectivity import *
+from ElementConnectivity import *
+from contourenvelope import *
 #}}}
 
@@ -82,5 +87,5 @@
 		self.qmu              = qmu()
 
-		self.results          = OrderedDict()
+		self.results          = results()
 		self.radaroverlay     = radaroverlay()
 		self.miscellaneous    = miscellaneous()
@@ -167,4 +172,279 @@
 		print ("model not consistent: %s" % string)
 		self.private.isconsistent=False
+		return self
+	# }}}
+
+	def 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
+
+		   Usage:
+		      md2=extract(md,area);
+
+		   Examples:
+		      md2=extract(md,'Domain.exp');
+		      md2=extract(md,md.mask.elementonfloatingice);
+
+		   See also: EXTRUDE, COLLAPSE
+		"""
+
+		#copy model
+		md1=copy.deepcopy(md)
+
+		#get elements that are inside area
+		flag_elem=FlagElements(md1,area)
+		if not numpy.any(flag_elem):
+			raise RuntimeError("extracted model is empty")
+
+		#kick out all elements with 3 dirichlets
+		spc_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
+		spc_node=numpy.unique(md1.mesh.elements[spc_elem,:]).astype(int)-1
+		flag=numpy.ones(md1.mesh.numberofvertices)
+		flag[spc_node]=0
+		pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements.astype(int)-1],axis=1)))[0]
+		flag_elem[pos]=0
+
+		#extracted elements and nodes lists
+		pos_elem=numpy.nonzero(flag_elem)[0]
+		pos_node=numpy.unique(md1.mesh.elements[pos_elem,:]).astype(int)-1
+
+		#keep track of some fields
+		numberofvertices1=md1.mesh.numberofvertices
+		numberofelements1=md1.mesh.numberofelements
+		numberofvertices2=numpy.size(pos_node)
+		numberofelements2=numpy.size(pos_elem)
+		flag_node=numpy.zeros(numberofvertices1)
+		flag_node[pos_node]=1
+
+		#Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
+		Pelem=numpy.zeros(numberofelements1)
+		Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
+		Pnode=numpy.zeros(numberofvertices1)
+		Pnode[pos_node]=numpy.arange(1,numberofvertices2+1)
+
+		#renumber the elements (some node won't exist anymore)
+		elements_1=copy.deepcopy(md1.mesh.elements)
+		elements_2=elements_1[pos_elem,:]
+		elements_2[:,0]=Pnode[elements_2[:,0].astype(int)-1]
+		elements_2[:,1]=Pnode[elements_2[:,1].astype(int)-1]
+		elements_2[:,2]=Pnode[elements_2[:,2].astype(int)-1]
+		if md1.mesh.dimension==3:
+			elements_2[:,3]=Pnode[elements_2[:,3].astype(int)-1]
+			elements_2[:,4]=Pnode[elements_2[:,4].astype(int)-1]
+			elements_2[:,5]=Pnode[elements_2[:,5].astype(int)-1]
+
+		#OK, now create the new model!
+
+		#take every field from model
+		md2=copy.deepcopy(md1)
+
+		#automatically modify fields
+
+		#loop over model fields
+		model_fields=vars(md1)
+		for fieldi in model_fields:
+			#get field
+			field=getattr(md1,fieldi)
+			fieldsize=numpy.shape(field)
+			if hasattr(field,'__dict__') and not ismember(fieldi,['results'])[0]:    #recursive call
+				object_fields=vars(field)
+				for fieldj in object_fields:
+					#get field
+					field=getattr(getattr(md1,fieldi),fieldj)
+					fieldsize=numpy.shape(field)
+					if len(fieldsize):
+						#size = number of nodes * n
+						if   fieldsize[0]==numberofvertices1:
+							setattr(getattr(md2,fieldi),fieldj,field[pos_node,:])
+						elif fieldsize[0]==numberofvertices1+1:
+							setattr(getattr(md2,fieldi),fieldj,numpy.vstack((field[pos_node,:],field[-1,:])))
+						#size = number of elements * n
+						elif fieldsize[0]==numberofelements1:
+							setattr(getattr(md2,fieldi),fieldj,field[pos_elem,:])
+			else:
+				if len(fieldsize):
+					#size = number of nodes * n
+					if   fieldsize[0]==numberofvertices1:
+						setattr(md2,fieldi,field[pos_node,:])
+					elif fieldsize[0]==numberofvertices1+1:
+						setattr(md2,fieldi,numpy.hstack((field[pos_node,:],field[-1,:])))
+					#size = number of elements * n
+					elif fieldsize[0]==numberofelements1:
+						setattr(md2,fieldi,field[pos_elem,:])
+
+		#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=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.uppervertex)))[0]
+			md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos].astype(int)-1]
+
+			md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
+			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.lowervertex)))[0]
+			md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos].astype(int)-1]
+
+			md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.upperelements)))[0]
+			md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos].astype(int)-1]
+
+			md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
+			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.lowerelements)))[0]
+			md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos].astype(int)-1]
+
+		#Initial 2d mesh 
+		if md1.mesh.dimension==3:
+			flag_elem_2d=flag_elem[numpy.arange(0,md1.mesh.numberofelements2d)]
+			pos_elem_2d=numpy.nonzero(flag_elem_2d)[0]
+			flag_node_2d=flag_node[numpy.arange(0,md1.mesh.numberofvertices2d)]
+			pos_node_2d=numpy.nonzero(flag_node_2d)[0]
+
+			md2.mesh.numberofelements2d=numpy.size(pos_elem_2d)
+			md2.mesh.numberofvertices2d=numpy.size(pos_node_2d)
+			md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:]
+			md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0].astype(int)-1]
+			md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1].astype(int)-1]
+			md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2].astype(int)-1]
+
+			md2.mesh.x2d=md1.mesh.x[pos_node_2d]
+			md2.mesh.y2d=md1.mesh.y[pos_node_2d]
+
+		#Edges
+		if len(numpy.shape(md2.mesh.edges))>1 and numpy.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some NaNs...
+			#renumber first two columns
+			pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
+			md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0].astype(int)-1]
+			md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1].astype(int)-1]
+			md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2].astype(int)-1]
+			md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3].astype(int)-1]
+			#remove edges when the 2 vertices are not in the domain.
+			md2.mesh.edges=md2.mesh.edges[numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
+			#Replace all zeros by -1 in the last two columns
+			pos=numpy.nonzero(md2.mesh.edges[:,2]==0)[0]
+			md2.mesh.edges[pos,2]=-1
+			pos=numpy.nonzero(md2.mesh.edges[:,3]==0)[0]
+			md2.mesh.edges[pos,3]=-1
+			#Invert -1 on the third column with last column (Also invert first two columns!!)
+			pos=numpy.nonzero(md2.mesh.edges[:,2]==-1)[0]
+			md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3]
+			md2.mesh.edges[pos,3]=-1
+			values=md2.mesh.edges[pos,1]
+			md2.mesh.edges[pos,1]=md2.mesh.edges[pos,0]
+			md2.mesh.edges[pos,0]=values
+			#Finally remove edges that do not belong to any element
+			pos=numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
+			md2.mesh.edges=numpy.delete(md2.mesh.edges,pos,axis=0)
+
+		#Penalties
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.vertex_pairing))):
+			for i in xrange(numpy.size(md1.diagnostic.vertex_pairing,axis=0)):
+				md2.diagnostic.vertex_pairing[i,:]=Pnode[md1.diagnostic.vertex_pairing[i,:]]
+			md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing[numpy.nonzero(md2.diagnostic.vertex_pairing[:,0])[0],:]
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.prognostic.vertex_pairing))):
+			for i in xrange(numpy.size(md1.prognostic.vertex_pairing,axis=0)):
+				md2.prognostic.vertex_pairing[i,:]=Pnode[md1.prognostic.vertex_pairing[i,:]]
+			md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing[numpy.nonzero(md2.prognostic.vertex_pairing[:,0])[0],:]
+
+		#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=numpy.zeros(numberofvertices2)
+			md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2].astype(int)-1]=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=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers)
+			md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2].astype(int)-1]=1
+			md2.mesh.vertexonboundary=numpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
+			#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)
+
+		#Boundary conditions: Dirichlets on new boundary
+		#Catch the elements that have not been extracted
+		orphans_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
+		orphans_node=numpy.unique(md1.mesh.elements[orphans_elem,:]).astype(int)-1
+		#Figure out which node are on the boundary between md2 and md1
+		nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
+		nodestoflag2=Pnode[nodestoflag1].astype(int)-1
+		if numpy.size(md1.diagnostic.spcvx)>1 and numpy.size(md1.diagnostic.spcvy)>2 and numpy.size(md1.diagnostic.spcvz)>2:
+			if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
+				md2.diagnostic.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
+				md2.diagnostic.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
+			else:
+				md2.diagnostic.spcvx[nodestoflag2]=float('NaN')
+				md2.diagnostic.spcvy[nodestoflag2]=float('NaN')
+				print "\n!! extract warning: spc values should be checked !!\n\n"
+			#put 0 for vz
+			md2.diagnostic.spcvz[nodestoflag2]=0
+		if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
+			md2.thermal.spctemperature[nodestoflag2,0]=1
+
+		#Diagnostic
+		if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.icefront))):
+			md2.diagnostic.icefront[:,0]=Pnode[md1.diagnostic.icefront[:,0].astype(int)-1]
+			md2.diagnostic.icefront[:,1]=Pnode[md1.diagnostic.icefront[:,1].astype(int)-1]
+			md2.diagnostic.icefront[:,-2]=Pelem[md1.diagnostic.icefront[:,-2].astype(int)-1]
+			if md1.mesh.dimension==3:
+				md2.diagnostic.icefront[:,2]=Pnode[md1.diagnostic.icefront[:,2].astype(int)-1]
+				md2.diagnostic.icefront[:,3]=Pnode[md1.diagnostic.icefront[:,3].astype(int)-1]
+			md2.diagnostic.icefront=md2.diagnostic.icefront[numpy.nonzero(numpy.logical_and(numpy.logical_and(md2.diagnostic.icefront[:,0],md2.diagnostic.icefront[:,1]),md2.diagnostic.icefront[:,-1]))[0],:]
+
+		#Results fields
+		if md1.results:
+			md2.results=results()
+			for solutionfield,field in md1.results.__dict__.iteritems():
+				if   isinstance(field,list):
+					setattr(md2.results,solutionfield,[])
+					#get time step
+					for i,fieldi in enumerate(field):
+						if isinstance(fieldi,results) and fieldi:
+							getattr(md2.results,solutionfield).append(results())
+							fieldr=getattr(md2.results,solutionfield)[i]
+							#get subfields
+							for solutionsubfield,subfield in fieldi.__dict__.iteritems():
+								if   numpy.size(subfield)==numberofvertices1:
+									setattr(fieldr,solutionsubfield,subfield[pos_node])
+								elif numpy.size(subfield)==numberofelements1:
+									setattr(fieldr,solutionsubfield,subfield[pos_elem])
+								else:
+									setattr(fieldr,solutionsubfield,subfield)
+						else:
+							getattr(md2.results,solutionfield).append(None)
+				elif isinstance(field,results):
+					setattr(md2.results,solutionfield,results())
+					if isinstance(field,results) and field:
+						fieldr=getattr(md2.results,solutionfield)
+						#get subfields
+						for solutionsubfield,subfield in field.__dict__.iteritems():
+							if   numpy.size(subfield)==numberofvertices1:
+								setattr(fieldr,solutionsubfield,subfield[pos_node])
+							elif numpy.size(subfield)==numberofelements1:
+								setattr(fieldr,solutionsubfield,subfield[pos_elem])
+							else:
+								setattr(fieldr,solutionsubfield,subfield)
+
+		#Keep track of pos_node and pos_elem
+		md2.mesh.extractedvertices=pos_node.astype(float)+1
+		md2.mesh.extractedelements=pos_elem.astype(float)+1
+
+		return md2
 	# }}}
 
@@ -242,5 +522,5 @@
 			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]))
+			z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
 		number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
 
@@ -402,5 +682,5 @@
 		#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)
+			md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
 
 		#special for thermal modeling:
Index: /issm/trunk/src/m/classes/modellist.m
===================================================================
--- /issm/trunk/src/m/classes/modellist.m	(revision 13974)
+++ /issm/trunk/src/m/classes/modellist.m	(revision 13975)
@@ -271,5 +271,4 @@
 			end
 
-
 			%now, tar all the files and then erase them.
 			eval(['!find -iname ''' name '-*'' > file_list.txt']);
@@ -302,5 +301,5 @@
 
 %First try and figure out if there is a special script for this particular cluster
-function_name=['BuildMultipleQueueingScript' cluster];
+function_name=['BuildMultipleQueueingScript' cluster]
 
 %some specific treatment of identical cluster, gemini, castor and pollux
@@ -348,5 +347,5 @@
 
 %First try and figure out if there is a special script for thie particular cluster
-function_name=['LaunchMultipleQueueJob' cluster];
+function_name=['LaunchMultipleQueueJob' cluster]
 
 %some specific treatment of identical cluster, gemini, castor and pollux
@@ -369,5 +368,4 @@
 %      LaunchMultipleQueueJobgemini(cluster,name,executionpath)
 
-
 %first, check we have the binary file and the queueing script
 if ~exist([ name '.queue'],'file'),
Index: /issm/trunk/src/m/classes/organizer.m
===================================================================
--- /issm/trunk/src/m/classes/organizer.m	(revision 13974)
+++ /issm/trunk/src/m/classes/organizer.m	(revision 13975)
@@ -10,5 +10,4 @@
 %      org = organizer(varargin)
 %
-%
 %   Examples:
 %      org = organizer('repository','Models/','prefix','AGU2015','steps',0);  %build an empty organizer object with a given repository
@@ -16,151 +15,151 @@
 classdef organizer
     properties (SetAccess=private) 
-		 % {{{
-		 currentstep   =0;
-	 end
+		% {{{
+		currentstep   =0;
+	end
     properties (SetAccess=public) 
-		 repository    ='./';
-		 prefix        ='model.';
-		 trunkprefix   ='';
-		 steps         =[];
-		 requestedsteps=[0];
-		 %}}}
-	 end
-	 methods
-		 function org=organizer(varargin) % {{{
+		repository    ='./';
+		prefix        ='model.';
+		trunkprefix   ='';
+		steps         =[];
+		requestedsteps=[0];
+		%}}}
+	end
+	methods
+		function org=organizer(varargin) % {{{
 
-			 %process options
-			 options=pairoptions(varargin{:});
+			%process options
+			options=pairoptions(varargin{:});
 
-			 %Get prefix
-			 prefix=getfieldvalue(options,'prefix','model.');
-			 if ~ischar(prefix),                            error('prefix is not a string'); end
-			 if ~strcmp(regexprep(prefix,'\s+',''),prefix), error('prefix should not have any white space'); end
-			 org.prefix=prefix;
+			%Get prefix
+			prefix=getfieldvalue(options,'prefix','model.');
+			if ~ischar(prefix),                            error('prefix is not a string'); end
+			if ~strcmp(regexprep(prefix,'\s+',''),prefix), error('prefix should not have any white space'); end
+			org.prefix=prefix;
 
-			 %Get repository
-			 repository=getfieldvalue(options,'repository','./');
-			 if ~ischar(repository),        error('repository is not a string'); end
-			 if exist(repository,'dir')~=7, error(['Directory ' repository ' not found']), end
-			 org.repository=repository;
+			%Get repository
+			repository=getfieldvalue(options,'repository','./');
+			if ~ischar(repository),        error('repository is not a string'); end
+			if exist(repository,'dir')~=7, error(['Directory ' repository ' not found']), end
+			org.repository=repository;
 
-			 %Get repository
-			 org.requestedsteps=getfieldvalue(options,'steps',0);
+			%Get steps
+			org.requestedsteps=getfieldvalue(options,'steps',0);
 
-			 %Get trunk prefix (only if provided by user)
-			 if exist(options,'trunkprefix'),
-				 trunkprefix=getfieldvalue(options,'trunkprefix','');
-				 if ~ischar(trunkprefix),                                 error('trunkprefix is not a string'); end
-				 if ~strcmp(regexprep(trunkprefix,'\s+',''),trunkprefix), error('trunkprefix should not have any white space'); end
-				 org.trunkprefix=trunkprefix;
-			 end
-		 end
-		 %}}}
-		 function disp(org) % {{{
-			 disp(sprintf('   Repository: ''%s''',org.repository));
-			 disp(sprintf('   Prefix:     ''%s''',org.prefix));
-			 if isempty(org.steps)
-				 disp('   no step');
-			 else
-				 for i=1:length(org.steps),
-					 disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
-				 end
-			 end
-		 end
-		 %}}}
-		 function md=load(org,string),% {{{
+			%Get trunk prefix (only if provided by user)
+			if exist(options,'trunkprefix'),
+				trunkprefix=getfieldvalue(options,'trunkprefix','');
+				if ~ischar(trunkprefix),                                 error('trunkprefix is not a string'); end
+				if ~strcmp(regexprep(trunkprefix,'\s+',''),trunkprefix), error('trunkprefix should not have any white space'); end
+				org.trunkprefix=trunkprefix;
+			end
+		end
+		%}}}
+		function disp(org) % {{{
+			disp(sprintf('   Repository: ''%s''',org.repository));
+			disp(sprintf('   Prefix:     ''%s''',org.prefix));
+			if isempty(org.steps)
+				disp('   no step');
+			else
+				for i=1:length(org.steps),
+					disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
+				end
+			end
+		end
+		%}}}
+		function md=load(org,string),% {{{
 
-			 %Get model path
-			 if ~ischar(string), error('argument provided is not a string'); end
-			 path=[org.repository '/' org.prefix string];
+			%Get model path
+			if ~ischar(string), error('argument provided is not a string'); end
+			path=[org.repository '/' org.prefix string];
 
-			 %figure out if the model is there
-			 if exist(path,'file'),
-				 struc=load(path,'-mat');
-				 name=char(fieldnames(struc));
-				 md=struc.(name);
-				 if nargout,
-					 varargout{1}=md;
-				 end
-			 else
-				 error(['Could not find ' path ]);
-			 end
-		 end%}}}
-		 function md=loadmodel(org,string),% {{{
+			%figure out if the model is there
+			if exist(path,'file'),
+				struc=load(path,'-mat');
+				name=char(fieldnames(struc));
+				md=struc.(name);
+				if nargout,
+					varargout{1}=md;
+				end
+			else
+				error(['Could not find ' path ]);
+			end
+		end%}}}
+		function md=loadmodel(org,string),% {{{
 
-			 %Get model path
-			 if ~ischar(string), error('argument provided is not a string'); end
-			 path=[org.repository '/' org.prefix string];
+			%Get model path
+			if ~ischar(string), error('argument provided is not a string'); end
+			path=[org.repository '/' org.prefix string];
 
-			 %figure out if the model is there, otherwise, we have to use the default path supplied by user.
-			 if exist(path,'file') | exist([path '.mat'],'file'),
-				 md=loadmodel(path);
-				 return;
-			 end
+			%figure out if the model is there, otherwise, we have to use the default path supplied by user.
+			if exist(path,'file') | exist([path '.mat'],'file'),
+				md=loadmodel(path);
+				return;
+			end
 
-			 %If we are here, the model has not been found. Try trunk prefix if provided
-			 if ~isempty(org.trunkprefix),
-				 path2=[org.repository '/' org.trunkprefix string];
-				 if ~exist(path2,'file'),
-					 error(['Could neither find ' path ', nor ' path2]);
-				 else
-					 disp(['--> Branching ' org.prefix ' from trunk ' org.trunkprefix]);
-					 md=loadmodel(path2);
-					 return;
-				 end
-			 else
-				 error(['Could not find ' path ]);
-			 end
-		 end%}}}
-		 function bool=perform(org,string) % {{{
-			 
-			 bool=false;
+			%If we are here, the model has not been found. Try trunk prefix if provided
+			if ~isempty(org.trunkprefix),
+				path2=[org.repository '/' org.trunkprefix string];
+				if ~exist(path2,'file'),
+					error(['Could find neither ' path ', nor ' path2]);
+				else
+					disp(['--> Branching ' org.prefix ' from trunk ' org.trunkprefix]);
+					md=loadmodel(path2);
+					return;
+				end
+			else
+				error(['Could not find ' path ]);
+			end
+		end%}}}
+		function bool=perform(org,string) % {{{
 
-			 %Some checks
-			 if ~ischar(string),                            error('Step provided should be a string'); end
-			 if ~strcmp(regexprep(string,'\s+',''),string), error('Step provided should not have any white space'); end
-			 if (org.currentstep>0 & ismember({string},{org.steps.string})) 
-				 error(['Step ' string ' already present. Change name']); 
-			 end
+			bool=false;
 
-			 %Add step
-			 org.steps(end+1).id=length(org.steps)+1;
-			 org.steps(end).string=string;
-			 org.currentstep=org.currentstep+1;
+			%Some checks
+			if ~ischar(string),                            error('Step provided should be a string'); end
+			if ~strcmp(regexprep(string,'\s+',''),string), error('Step provided should not have any white space'); end
+			if (org.currentstep>0 & ismember({string},{org.steps.string})) 
+				error(['Step ' string ' already present. Change name']); 
+			end
 
-			 %if requestedsteps = 0, print all steps in org 
-			 if any(org.requestedsteps==0),
-				 if org.currentstep==1,
-					 disp(sprintf('   prefix: %s',org.prefix));
-				 end
-				 disp(sprintf('   step #%2i : %s',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
-			 end
+			%Add step
+			org.steps(end+1).id=length(org.steps)+1;
+			org.steps(end).string=string;
+			org.currentstep=org.currentstep+1;
 
-			 %Ok, now if currentstep is a member of steps, return true
-			 if ismember(org.currentstep,org.requestedsteps),
-				 disp(sprintf('\n   step #%i : %s\n',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
-				 bool=true;
-			 end
+			%if requestedsteps = 0, print all steps in org 
+			if any(org.requestedsteps==0),
+				if org.currentstep==1,
+					disp(sprintf('   prefix: %s',org.prefix));
+				end
+				disp(sprintf('   step #%2i : %s',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
+			end
 
-			 %assign org back to calling workspace
-			 assignin('caller',inputname(1),org);
+			%Ok, now if currentstep is a member of steps, return true
+			if ismember(org.currentstep,org.requestedsteps),
+				disp(sprintf('\n   step #%i : %s\n',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
+				bool=true;
+			end
 
-		 end%}}}
-		 function savemodel(org,md) % {{{
+			%assign org back to calling workspace
+			assignin('caller',inputname(1),org);
 
-			 %check
-			 if (org.currentstep==0), error('Cannot save model because organizer (org) is empty! Make sure you did not skip any perform call'); end
-			 if (org.currentstep>length(org.steps)), error('Cannot save model because organizer (org) is not up to date!'); end
+		end%}}}
+		function savemodel(org,md) % {{{
 
-			 name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
-			 disp(['saving model as: ' name]);
-			 
-			 %check that md is a model
-			 if ~isa(md,'model'), warning('third argument is not a model'); end
-			 if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
+			%check
+			if (org.currentstep==0), error('Cannot save model because organizer (org) is empty! Make sure you did not skip any perform call'); end
+			if (org.currentstep>length(org.steps)), error('Cannot save model because organizer (org) is not up to date!'); end
 
-			 %save model
-			 save(name,'md','-v7.3');
-		 end%}}}
+			name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
+			disp(['saving model as: ' name]);
+
+			%check that md is a model
+			if ~isa(md,'model'), warning('second argument is not a model'); end
+			if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
+
+			%save model
+			save(name,'md','-v7.3');
+		end%}}}
 	end
 end
Index: /issm/trunk/src/m/classes/organizer.py
===================================================================
--- /issm/trunk/src/m/classes/organizer.py	(revision 13975)
+++ /issm/trunk/src/m/classes/organizer.py	(revision 13975)
@@ -0,0 +1,176 @@
+import os.path
+from collections import OrderedDict
+from pairoptions import *
+from loadvars import *
+from loadmodel import *
+from savevars import *
+from model import model
+
+class organizer(object):
+	"""
+	ORGANIZER class definition
+
+	   Supported options:
+	      repository: directory where all models will be saved
+	      prefix:     prefix for saved model names
+	      steps:      requested steps
+	      trunkprefix:prefix of previous run with a different prefix. Used to branch.
+
+	   Usage:
+	      org = organizer(varargin)
+
+	   Examples:
+	      org = organizer('repository','Models/','prefix','AGU2015','steps',0);  %build an empty organizer object with a given repository
+	"""
+
+	def __init__(self,*args):    # {{{
+		self._currentstep  =0
+		self.repository    ='./'
+		self.prefix        ='model.'
+		self.trunkprefix   =''
+		self.steps         =[]
+		self.requestedsteps=[0]
+
+		#process options
+		options=pairoptions(*args)
+
+		#Get prefix
+		prefix=options.getfieldvalue('prefix','model.')
+		if not isinstance(prefix,(str,unicode)):
+			raise TypeError("prefix is not a string")
+		if not strcmp(prefix,prefix.strip()) or len(prefix.split()) > 1:
+			raise TypeError("prefix should not have any white space")
+		self.prefix=prefix
+
+		#Get repository
+		repository=options.getfieldvalue('repository','./')
+		if not isinstance(repository,(str,unicode)):
+			raise TypeError("repository is not a string")
+		if not os.path.isdir(repository):
+			raise IOError("Directory '%s' not found" % repository)
+		self.repository=repository
+
+		#Get steps
+		self.requestedsteps=options.getfieldvalue('steps',[0])
+
+		#Get trunk prefix (only if provided by user)
+		if options.exist('trunkprefix'):
+			trunkprefix=options.getfieldvalue('trunkprefix','')
+			if not isinstance(trunkprefix,(str,unicode)):
+				raise TypeError("trunkprefix is not a string")
+			if not strcmp(trunkprefix,trunkprefix.strip()) or len(trunkprefix.split()) > 1:
+				raise TypeError("trunkprefix should not have any white space")
+			self.trunkprefix=trunkprefix
+	#}}}
+
+	def __repr__(self):    # {{{
+		s =""
+
+		s+="%s\n" % "   Repository: '%s'" % self.repository
+		s+="%s\n" % "   Prefix:     '%s'" % self.prefix
+		if not self.steps:
+			s+="%s\n" % "   no step"
+		else:
+			for step in self.steps:
+				s+="%s\n" % "   step #%2i: '%s'",step['id'],step['string']
+	#}}}
+
+	def load(self,string):    # {{{
+
+		#Get model path
+		if not isinstance(string,(str,unicode)):
+			raise TypeError("argument provided is not a string")
+		path=os.path.join(self.repository,self.prefix+string)
+
+		#figure out if the model is there
+		if os.path.exists(path):
+			struc=loadvars(path)
+			name=name=[key for key in struc.iterkeys()]
+			md=struc.name[0]
+		else:
+			raise IOError("Could not find '%s'" % path)
+
+		return md
+	#}}}
+
+	def loadmodel(self,string):    # {{{
+
+		#Get model path
+		if not isinstance(string,(str,unicode)):
+			raise TypeError("argument provided is not a string")
+		path=os.path.join(self.repository,self.prefix+string)
+
+		#figure out if the model is there, otherwise, we have to use the default path supplied by user.
+		if os.path.exists(path):
+			md=loadmodel(path)
+			return md
+
+		#If we are here, the model has not been found. Try trunk prefix if provided
+		if self.trunkprefix:
+			path2=os.path.join(self.repository,self.trunkprefix+string)
+			if not os.path.exists(path2):
+				raise IOError("Could find neither '%s' nor '%s'" % (path,path2))
+			else:
+				print "--> Branching '%s' from trunk '%s'" % (self.prefix,self.trunkprefix)
+				md=loadmodel(path2)
+				return md
+		else:
+			raise IOerror("Could not find '%s'" % path)
+	#}}}
+
+	def perform(self,string):    # {{{
+
+		bool=False
+
+		#Some checks
+		if not isinstance(string,(str,unicode)):
+			raise TypeError("Step provided should be a string")
+		if not strcmp(string,string.strip()) or len(string.split()) > 1:
+			raise TypeError("Step provided should not have any white space")
+		if self._currentstep>0 and string in [step['string'] for step in self.steps]:
+			raise RuntimeError("Step '%s' already present. Change name" % string) 
+
+		#Add step
+		self.steps.append(OrderedDict())
+		self.steps[-1]['id']=len(self.steps)
+		self.steps[-1]['string']=string
+		self._currentstep+=1
+
+		#if requestedsteps = 0, print all steps in self 
+		if 0 in self.requestedsteps:
+			if self._currentstep==1:
+				print "   prefix: %s" % self.prefix
+			print "   step #%i : %s" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])
+
+		#Ok, now if _currentstep is a member of steps, return true
+		if self._currentstep in self.requestedsteps:
+			print "\n   step #%i : %s\n" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])
+			bool=True
+
+		#assign self back to calling workspace
+		# (no need, since Python modifies class instance directly)
+
+		return bool
+	#}}}
+
+	def savemodel(self,md):    # {{{
+
+		#check
+		if self._currentstep==0:
+			raise RuntimeError("Cannot save model because organizer (org) is empty! Make sure you did not skip any perform call")
+		if self._currentstep>len(self.steps):
+			raise RuntimeError("Cannot save model because organizer (org) is not up to date!")
+
+		name=os.path.join(self.repository,self.prefix+self.steps[self._currentstep-1]['string'])
+		print "saving model as: '%s'" % name
+
+		#check that md is a model
+		if not isinstance(md,model):
+			print("second argument is not a model")
+		if self._currentstep>len(self.steps):
+			raise RuntimeError("organizer error message: element with id %d not found" % self._currentstep)
+
+		#save model
+		savevars(name,'md',md)
+	#}}}
+
Index: /issm/trunk/src/m/classes/pairoptions.m
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.m	(revision 13974)
+++ /issm/trunk/src/m/classes/pairoptions.m	(revision 13975)
@@ -175,5 +175,5 @@
 
 			%some argument checking: 
-			if nargin~=2 & nargin~=3,
+			if nargin~=2 && nargin~=3,
 				help getfieldvalue
 				error('getfieldvalue error message: bad usage');
@@ -185,9 +185,8 @@
 
 			%Recover option
-			for i=1:size(obj.list,1),
-				if strcmpi(obj.list{i,1},field)
-					value=obj.list{i,2};
-					return
-				end
+			pos=find(strcmpi(obj.list(:,1),field));
+			if ~isempty(pos),
+				value=obj.list{pos(1),2}; %ignore extra entry
+				return;
 			end
 
Index: /issm/trunk/src/m/classes/pairoptions.py
===================================================================
--- /issm/trunk/src/m/classes/pairoptions.py	(revision 13974)
+++ /issm/trunk/src/m/classes/pairoptions.py	(revision 13975)
@@ -41,5 +41,5 @@
 			else:
 				#option is not a string, ignore it
-				print "WARNING: option number %d '%s' is not a string and will be ignored." % (i+1,type(arg[2*i]))
+				print "WARNING: option number %d is not a string and will be ignored." % (i+1)
 	# }}}
 
@@ -53,5 +53,5 @@
 
 	def addfielddefault(self,field,value):    # {{{
-		"""ADDFIELDDEFAULT - add a field to an options list if it does not exist"""
+		"""ADDFIELDDEFAULT - add a field to an options list if it does not already exist"""
 		if isinstance(field,(str,unicode)):
 			if field not in self.list:
@@ -128,15 +128,17 @@
 	# }}}
 
-#	function num = fieldoccurences(obj,field), % {{{
-#	%FIELDOCCURENCES - get number of occurence of a field
-#
-#		%check input 
-#		if ~ischar(field),
-#			error('fieldoccurences error message: field should be a string');
-#		end
-#
-#		%get number of occurence
-#		num=sum(strcmpi(field,obj.list(:,1)));
-#	end % }}}
+	#def fieldoccurences(self,field): #{{{
+	#	'''
+	#	FIELDOCCURENCES - get number of occurence of a field
+	#	'''
+	#
+	#	#check input 
+	#	if not isinstance(field,(str,unicode)):
+	#		raise TypeError("fieldoccurences error message: field should be a string")
+
+	#	#get number of occurence
+	#	# ??
+	#	#return num
+	#	#% }}}
 
 	def getfieldvalue(self,field,default=None):    # {{{
Index: /issm/trunk/src/m/classes/planetmesh.m
===================================================================
--- /issm/trunk/src/m/classes/planetmesh.m	(revision 13974)
+++ /issm/trunk/src/m/classes/planetmesh.m	(revision 13975)
@@ -17,5 +17,5 @@
 		numberofelements            = 0;
 		numberofvertices            = 0;
-		
+
 		lat                         = NaN
 		long                        = NaN
@@ -103,5 +103,5 @@
 			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');
Index: /issm/trunk/src/m/classes/plotoptions.py
===================================================================
--- /issm/trunk/src/m/classes/plotoptions.py	(revision 13975)
+++ /issm/trunk/src/m/classes/plotoptions.py	(revision 13975)
@@ -0,0 +1,127 @@
+from collections import OrderedDict, Counter, defaultdict
+from pairoptions import *
+
+class plotoptions(object):
+	'''
+	PLOTOPTIONS class definition
+
+		Usage:
+			plotoptions=plotoptions(*arg)
+	'''
+
+	def __init__(self,*arg):
+		self.numberofplots = 0
+		self.figurenumber  = 1
+		self.list          = OrderedDict()
+
+		self.buildlist(*arg)
+
+	def __repr__(self): #{{{
+		s="\n"
+		s+="	numberofplots: %i\n" % self.numberofplots
+		s+="	figurenumber: %i\n"  % self.figurenumber
+		if self.list:
+			s+="	list: (%ix%i)\n" % (len(self.list),2)
+			for item in self.list.iteritems():
+				#s+="	options of plot number %i\n" % item
+				if   isinstance(item[1],(str,unicode)):
+					s+="	field: %-10s value: '%s'\n" % (item[0],item[1])
+				elif isinstance(item[1],(bool,int,long,float)):
+					s+="	field: %-10s value: '%g'\n" % (item[0],item[1])
+				else:
+					s+="	field: %-10s value: '%s'\n" % (item[0],item[1])
+		else:
+			s+="	list: empty\n"
+		return s
+	#}}}
+	def buildlist(self,*arg): #{{{
+		#check length of input
+		if len(arg) % 2:
+			raise TypeError('error: an even number of options is required')
+
+		#go through args and build list (like pairoptions)
+		rawoptions=pairoptions(*arg)
+		numoptions=len(arg)/2
+		rawlist=[] # cannot be a dict since they do not support duplicate keys
+
+		for i in xrange(numoptions):
+			if isinstance(arg[2*i],(str,unicode)):
+				rawlist.append([arg[2*i],arg[2*i+1]])
+			else:
+				#option is not a string, ignore it
+				print "WARNING: option number %d is not a string and will be ignored." % (i+1)
+
+		#get figure number 
+		self.figurenumber=rawoptions.getfieldvalue('figure',1)
+
+		#get number of subplots 
+		numberofplots=Counter(x for sublist in rawlist for x in sublist if isinstance(x,(str,unicode)))['data']
+		self.numberofplots=numberofplots
+
+		#figure out whether alloptions flag is on
+		if rawoptions.getfieldvalue('alloptions','off') is 'on':
+			allflag=1
+		else:
+			allflag=0
+
+		#initialize self.list (will need a list of dict's (or nested dict) for numberofplots>1)
+		#self.list=defaultdict(dict)
+		for i in xrange(numberofplots):
+			self.list[i]=pairoptions()
+
+		#process plot options
+		for i in xrange(len(rawlist)):
+
+			#if alloptions flag is on, apply to all plots
+			if (allflag and 'data' not in rawlist[i][0] and '#' not in rawlist[i][0]):
+				
+				for j in xrange(numberofplots):
+					self.list[j].addfield(rawlist[i][0],rawlist[i][1])
+
+			elif '#' in rawlist[i][0]:
+
+				#get subplots associated
+				string=rawlist[i][0].split('#')
+				plotnums=string[-1].split(',')
+				field=string[0]
+
+				#loop over plotnums
+				for k in xrange(len(plotnums)):
+					plotnum=plotnums[k]
+
+					#Empty
+					if not plotnum: continue
+
+					# '#all'
+					elif 'all' in plotnum:
+						for j in xrange(numberofplots):
+							self.list[j].addfield(field,rawlist[i][1])
+
+					# '#i-j'
+					elif '-' in plotnum:
+						nums=plotnum.split('-')
+						if len(nums)!=2: continue
+						if False in [x.isdigit() for x in nums]:
+							raise ValueError('error: in option i-j both i and j must be integers')
+						for j in xrange(int(nums[0])-1,int(nums[1])):
+							self.list[j].addfield(field,rawlist[i][1])	
+
+					# Deal with #i
+					else:
+						#assign to subplot
+						if int(plotnum)>numberofplots:
+							raise ValueError('error: %s cannot be assigned %d which exceeds the number of subplots' % (field,plotnum))
+						self.list[int(plotnum)-1].addfield(field,rawlist[i][1])
+			else:
+				
+				#go through all subplots and assign key-value pairs
+				j=0
+				while j <= numberofplots-1:
+					if not self.list[j].exist(rawlist[i][0]):
+						self.list[j].addfield(rawlist[i][0],rawlist[i][1])
+						break
+					else:
+						j=j+1
+				if j+1>numberofplots:
+					print "WARNING: too many instances of '%s' in options" % rawlist[i][0]
+	#}}}
Index: /issm/trunk/src/m/classes/prognostic.m
===================================================================
--- /issm/trunk/src/m/classes/prognostic.m	(revision 13974)
+++ /issm/trunk/src/m/classes/prognostic.m	(revision 13975)
@@ -12,4 +12,5 @@
 		 vertex_pairing         = NaN;
 		 penalty_factor         = 0;
+		 requested_outputs      = NaN;
 	end
 	methods
@@ -45,4 +46,7 @@
 			md = checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
 			md = checkfield(md,'prognostic.min_thickness','>',0);
+			if ~isempty(md.prognostic.requested_outputs),
+				md = checkfield(md,'prognostic.requested_outputs','size',[NaN 1]);
+			end
 
 		end % }}}
@@ -57,4 +61,5 @@
 			fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
 			fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
+			fielddisplay(obj,'requested_outputs','additional outputs requested');
 
 		end % }}}
@@ -66,4 +71,5 @@
 			WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
 			WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
+			WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/prognostic.py
===================================================================
--- /issm/trunk/src/m/classes/prognostic.py	(revision 13974)
+++ /issm/trunk/src/m/classes/prognostic.py	(revision 13975)
@@ -23,4 +23,5 @@
 		self.vertex_pairing         = float('NaN')
 		self.penalty_factor         = 0
+		self.requested_outputs      = float('NaN')
 
 		#set defaults
@@ -35,4 +36,5 @@
 		string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
 		string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
+		string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
 
 		return string
@@ -67,4 +69,6 @@
 		md = checkfield(md,'prognostic.stabilization','values',[0,1,2,3])
 		md = checkfield(md,'prognostic.min_thickness','>',0)
+		if not md.prognostic.requested_outputs:
+			md = checkfield(md,'prognostic.requested_outputs','size',[float('NaN'),1])
 
 		return md
@@ -78,4 +82,5 @@
 		WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
 		WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
+		WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
 	# }}}
 
Index: /issm/trunk/src/m/classes/qmu.m
===================================================================
--- /issm/trunk/src/m/classes/qmu.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu.m	(revision 13975)
@@ -33,5 +33,5 @@
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
-	
+
 		end % }}}
 		function md = checkconsistency(obj,md,solution,analyses) % {{{
@@ -142,5 +142,8 @@
 		function marshall(obj,fid) % {{{
 			WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
-			if ~obj.isdakota, return; end
+			if ~obj.isdakota, 
+				WriteData(fid,'data',false,'enum',QmuMassFluxSegmentsPresentEnum,'format','Boolean');
+				return; 
+			end
 			WriteData(fid,'object',obj,'fieldname','partition','format','DoubleMat','mattype',2);
 			WriteData(fid,'object',obj,'fieldname','numberofpartitions','format','Integer');
@@ -148,5 +151,11 @@
 			WriteData(fid,'object',obj,'fieldname','variabledescriptors','format','StringArray');
 			WriteData(fid,'object',obj,'fieldname','responsedescriptors','format','StringArray');
-			WriteData(fid,'object',obj,'fieldname','mass_flux_segments','format','MatArray');
+			if ~isempty(obj.mass_flux_segments), 
+				WriteData(fid,'data',obj.mass_flux_segments,'enum',MassFluxSegmentsEnum,'format','MatArray');
+				flag=true; 
+			else 
+				flag=false; 
+			end
+			WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum,'format','Boolean');
 		end % }}}
 	end
Index: /issm/trunk/src/m/classes/qmu.py
===================================================================
--- /issm/trunk/src/m/classes/qmu.py	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu.py	(revision 13975)
@@ -45,5 +45,4 @@
 		return self
 	#}}}
-
 	def checkconsistency(self,md,solution,analyses):    # {{{
 
@@ -68,5 +67,4 @@
 		return md
 	# }}}
-
 	def __repr__(self):    # {{{
 		s ='   qmu parameters:\n'
@@ -141,8 +139,8 @@
 		return s
 	# }}}
-		
 	def marshall(self,fid):    # {{{
 		WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
 		if not self.isdakota:
+			WriteData(fid,'data',False,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
 			return
 		WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
@@ -151,5 +149,10 @@
 		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')
+		if not self.mass_flux_segments:
+			WriteData(fid,'data',self.mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');
+			flag=True; 
+		else:
+			flag=False; 
+		WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
 	# }}}
 
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m	(revision 13975)
@@ -49,5 +49,5 @@
         params   =struct();
     end
-    
+
     methods
         function [dm]=dakota_method(method)
@@ -828,5 +828,5 @@
 
                     end
-                    
+
 %  if more than one argument, issue warning
 
@@ -852,5 +852,5 @@
                 disp(sprintf('    responses: %s'      ,string_cell(dm(i).responses)));
                 disp(sprintf('       ghspec: %s\n'    ,string_cell(dm(i).ghspec)));
-    
+
 %  display the parameters within the object
 
@@ -860,5 +860,5 @@
                     maxlen=max(maxlen,length(fnames{j}));
                 end
-    
+
                 for j=1:numel(fnames)
                     disp(sprintf(['       params.%-' num2str(maxlen+1) 's: %s'],...
@@ -870,3 +870,2 @@
     end
 end
-
Index: /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m	(revision 13975)
@@ -46,5 +46,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'npsol'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -64,5 +64,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'conmin'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -80,5 +80,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'optpp'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -120,5 +120,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'apps'}
         param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
@@ -140,5 +140,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'coliny'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -212,5 +212,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'ncsu'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -226,5 +226,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'jega'}
         param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
@@ -282,5 +282,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'lsq'}
         switch dm.method
@@ -344,5 +344,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'nond'}
         switch dm.method
@@ -426,5 +426,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'dace'}
         switch dm.method
@@ -484,5 +484,5 @@
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
         end
-        
+
     case {'param'}
         param_write(fid,sbeg,'output',' ','\n',dm.params);
@@ -512,5 +512,5 @@
             case {'multidim_parameter_study'}
                 param_write(fid,sbeg,'partitions',' = ','\n',dm.params);
-            
+
             otherwise
                 error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
Index: /issm/trunk/src/m/classes/qmu/continuous_design.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/continuous_design.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/continuous_design.m	(revision 13975)
@@ -39,5 +39,5 @@
         scale     = 1.;
     end
-    
+
     methods
         function [cdv]=continuous_design(varargin)
@@ -65,5 +65,5 @@
                     cdv(asizec{:})=continuous_design;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -212,5 +212,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
Index: /issm/trunk/src/m/classes/qmu/continuous_state.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/continuous_state.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/continuous_state.m	(revision 13975)
@@ -35,5 +35,5 @@
         upper     = Inf;
     end
-    
+
     methods
         function [csv]=continuous_state(varargin)
@@ -61,5 +61,5 @@
                     csv(asizec{:})=continuous_state;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -177,5 +177,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
Index: /issm/trunk/src/m/classes/qmu/least_squares_term.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/least_squares_term.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/least_squares_term.m	(revision 13975)
@@ -35,5 +35,5 @@
         weight    = 1.;
     end
-    
+
     methods
         function [lst]=least_squares_term(varargin)
@@ -54,5 +54,5 @@
                         lst(asizec{:})=least_squares_term;
                         clear asizec
-                    
+
                         if ischar(varargin{1})
                             varargin{1}=cellstr(varargin{1});
@@ -169,5 +169,5 @@
         end
     end
-    
+
     methods (Static)
         function [rdesc]=dakota_write(fidi,dresp,rdesc)
Index: /issm/trunk/src/m/classes/qmu/linear_equality_constraint.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/linear_equality_constraint.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/linear_equality_constraint.m	(revision 13975)
@@ -35,5 +35,5 @@
         scale     = 1.;
     end
-    
+
     methods
         function [lec]=linear_equality_constraint(varargin)
@@ -69,5 +69,5 @@
                     lec(asizec{:})=linear_equality_constraint;
                     clear asizec
-                    
+
                     for i=1:numel(lec)
                         if (size(varargin{1},1) > 1)
@@ -167,5 +167,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
Index: /issm/trunk/src/m/classes/qmu/linear_inequality_constraint.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/linear_inequality_constraint.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/linear_inequality_constraint.m	(revision 13975)
@@ -37,5 +37,5 @@
         scale     = 1.;
     end
-    
+
     methods
         function [lic]=linear_inequality_constraint(varargin)
@@ -77,5 +77,5 @@
                     lic(asizec{:})=linear_inequality_constraint;
                     clear asizec
-                    
+
                     for i=1:numel(lic)
                         if (size(varargin{1},1) > 1)
@@ -189,5 +189,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
@@ -203,3 +203,2 @@
     end
 end
-
Index: /issm/trunk/src/m/classes/qmu/nonlinear_equality_constraint.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/nonlinear_equality_constraint.m	(revision 13975)
@@ -35,5 +35,5 @@
         scale     = 1.;
     end
-    
+
     methods
         function [nec]=nonlinear_equality_constraint(varargin)
@@ -61,5 +61,5 @@
                     nec(asizec{:})=nonlinear_equality_constraint;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -171,5 +171,5 @@
         end
     end
-    
+
     methods (Static)
         function [rdesc]=dakota_write(fidi,dresp,rdesc)
Index: /issm/trunk/src/m/classes/qmu/nonlinear_inequality_constraint.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/nonlinear_inequality_constraint.m	(revision 13975)
@@ -37,5 +37,5 @@
         scale     = 1.;
     end
-    
+
     methods
         function [nic]=nonlinear_inequality_constraint(varargin)
@@ -69,5 +69,5 @@
                     nic(asizec{:})=nonlinear_inequality_constraint;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -189,5 +189,5 @@
         end
     end
-    
+
     methods (Static)
         function [rdesc]=dakota_write(fidi,dresp,rdesc)
Index: /issm/trunk/src/m/classes/qmu/normal_uncertain.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/normal_uncertain.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/normal_uncertain.m	(revision 13975)
@@ -37,5 +37,5 @@
         upper     = Inf;
     end
-    
+
     methods
         function [nuv]=normal_uncertain(varargin)
@@ -69,5 +69,5 @@
                     nuv(asizec{:})=normal_uncertain;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -193,5 +193,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
Index: /issm/trunk/src/m/classes/qmu/objective_function.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/objective_function.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/objective_function.m	(revision 13975)
@@ -35,5 +35,5 @@
         weight    = 1.;
     end
-    
+
     methods
         function [of]=objective_function(varargin)
@@ -54,5 +54,5 @@
                         of(asizec{:})=objective_function;
                         clear asizec
-                    
+
                         if ischar(varargin{1})
                             varargin{1}=cellstr(varargin{1});
@@ -169,5 +169,5 @@
         end
     end
-    
+
     methods (Static)
         function [rdesc]=dakota_write(fidi,dresp,rdesc)
Index: /issm/trunk/src/m/classes/qmu/response_function.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/response_function.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/response_function.m	(revision 13975)
@@ -37,5 +37,5 @@
         grell     =[];
     end
-    
+
     methods
         function [rf]=response_function(varargin)
@@ -56,5 +56,5 @@
                         rf(asizec{:})=response_function;
                         clear asizec
-                    
+
                         if ischar(varargin{1})
                             varargin{1}=cellstr(varargin{1});
@@ -166,5 +166,5 @@
         end
     end
-    
+
     methods (Static)
         function [rdesc]=dakota_write(fidi,dresp,rdesc)
@@ -178,5 +178,5 @@
             [rdesc]=rlist_write(fidi,'response_functions','response_function',rf,rdesc);
         end
-        
+
         function []=dakota_rlev_write(fidi,dresp,params)
 
Index: /issm/trunk/src/m/classes/qmu/uniform_uncertain.m
===================================================================
--- /issm/trunk/src/m/classes/qmu/uniform_uncertain.m	(revision 13974)
+++ /issm/trunk/src/m/classes/qmu/uniform_uncertain.m	(revision 13975)
@@ -32,5 +32,5 @@
         upper     = Inf;
     end
-    
+
     methods
         function [uuv]=uniform_uncertain(varargin)
@@ -64,5 +64,5 @@
                     uuv(asizec{:})=uniform_uncertain;
                     clear asizec
-                    
+
                     if ischar(varargin{1})
                         varargin{1}=cellstr(varargin{1});
@@ -152,5 +152,5 @@
         end
     end
-    
+
     methods (Static)
         function []=dakota_write(fidi,dvar)
Index: /issm/trunk/src/m/classes/results.py
===================================================================
--- /issm/trunk/src/m/classes/results.py	(revision 13975)
+++ /issm/trunk/src/m/classes/results.py	(revision 13975)
@@ -0,0 +1,59 @@
+import numpy
+from pairoptions import *
+from fielddisplay import *
+from MatlabFuncs import *
+from EnumDefinitions import *
+from WriteData import *
+
+class results(object):
+	"""
+	RESULTS class definition
+
+	   Usage:
+	      results=results();
+	"""
+
+	def __init__(self,*args):    # {{{
+		pass
+	# }}}
+
+	def __repr__(self):    # {{{
+		s ="   Model results:\n"
+
+		if 'step' in self.__dict__:
+			s+="%s\n" % fielddisplay(self,'step',"step number")
+		if 'time' in self.__dict__:
+			s+="%s\n" % fielddisplay(self,'time',"time value")
+		if 'SolutionType' in self.__dict__:
+			s+="%s\n" % fielddisplay(self,'SolutionType',"solution type")
+
+		for name in self.__dict__.iterkeys():
+			if name not in ['step','time','SolutionType','errlog','outlog']:
+				if   isinstance(getattr(self,name),list):
+					s+="%s\n" % fielddisplay(self,name,"model results list")
+				elif isinstance(getattr(self,name),results):
+					s+="%s\n" % fielddisplay(self,name,"model results case")
+				else:
+					s+="%s\n" % fielddisplay(self,name,"")
+
+		if 'errlog' in self.__dict__:
+			s+="%s\n" % fielddisplay(self,'errlog',"error log file")
+		if 'outlog' in self.__dict__:
+			s+="%s\n" % fielddisplay(self,'outlog',"output log file")
+
+		return s
+	# }}}
+
+	def setdefaultparameters(self):    # {{{
+		#do nothing
+		return self
+	# }}}
+
+	def checkconsistency(self,md,solution,analyses):    # {{{
+		return md
+	# }}}
+
+	def marshall(self,fid):    # {{{
+		pass
+	# }}}
+
Index: /issm/trunk/src/m/classes/rifts.m
===================================================================
--- /issm/trunk/src/m/classes/rifts.m	(revision 13974)
+++ /issm/trunk/src/m/classes/rifts.m	(revision 13975)
@@ -38,8 +38,10 @@
 					md = checkmessage(md,['model should be processed for rifts (run meshprocessrifts)!']);
 				end
-				md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
+				for i=1:numrifts,
+					md = checkfield(md,sprintf('rifts.riftstruct(%d).fill',i),'values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
+				end
 			else
 				if ~isnans(obj.riftstruct),
-					md = checkmessage(md,['riftstruct shoud be NaN since numrifts is 0!']);
+					md = checkmessage(md,['riftstruct should be NaN since numrifts is 0!']);
 				end
 			end
Index: /issm/trunk/src/m/classes/rifts.py
===================================================================
--- /issm/trunk/src/m/classes/rifts.py	(revision 13974)
+++ /issm/trunk/src/m/classes/rifts.py	(revision 13975)
@@ -18,6 +18,6 @@
 	def __init__(self):
 		# {{{ Properties
-		self.riftstruct     = float('NaN')
-		self.riftproperties = float('NaN')
+		self.riftstruct     = []
+		self.riftproperties = []
 
 		#set defaults
@@ -53,8 +53,9 @@
 				#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()])
+			for i,rift in enumerate(self.riftstruct):
+				md = checkfield(md,"rifts.riftstruct[%d]['fill']" % i,'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!")
+			if self.riftstruct and numpy.any(numpy.logical_not(isnans(self.riftstruct))):
+				md.checkmessage("riftstruct should be NaN since numrifts is 0!")
 
 		return md
@@ -70,18 +71,18 @@
 
 		numpairs=0
-		for i in xrange(0,numrifts):
-			numpairs+=numpy.size(self.riftstruct[i].penaltypairs,0)
+		for rift in self.riftstruct:
+			numpairs+=numpy.size(rift['penaltypairs'],axis=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']
+		for rift in self.riftstruct:
+			numpairsforthisrift=numpy.size(rift['penaltypairs'],0)
+			data[count:count+numpairsforthisrift,0:7]=rift['penaltypairs']
+			data[count:count+numpairsforthisrift,7]=rift['fill']
+			data[count:count+numpairsforthisrift,8]=rift['friction']
+			data[count:count+numpairsforthisrift,9]=rift['fraction']
+			data[count:count+numpairsforthisrift,10]=rift['fractionincrement']
+			data[count:count+numpairsforthisrift,11]=rift['state'].reshape(-1)
 			count+=numpairsforthisrift
 
Index: /issm/trunk/src/m/classes/solver.m
===================================================================
--- /issm/trunk/src/m/classes/solver.m	(revision 13974)
+++ /issm/trunk/src/m/classes/solver.m	(revision 13975)
@@ -98,5 +98,5 @@
 					 else
 						 %option with value. value can be string or scalar
-						 if isscalar(optionvalue),
+						 if isnumeric(optionvalue),
 							 fprintf(fid,'-%s %g\n',optionname,optionvalue);
 						 elseif ischar(optionvalue),
Index: /issm/trunk/src/m/classes/surfaceforcings.m
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.m	(revision 13974)
+++ /issm/trunk/src/m/classes/surfaceforcings.m	(revision 13975)
@@ -12,4 +12,6 @@
 		isdelta18o = 0;
 		hc = NaN;
+		href = NaN;
+		smbref = NaN;
 		smb_pos_max = NaN;
 		smb_pos_min = NaN;
@@ -35,5 +37,5 @@
 		end % }}}
 		function obj = setdefaultparameters(obj) % {{{
-		  
+
 		  %pdd method not used in default mode
 		  obj.ispdd=0;
@@ -60,4 +62,6 @@
 				elseif(obj.issmbgradients)
 					md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.href','forcing',1,'NaN',1);
+					md = checkfield(md,'surfaceforcings.smbref','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);
@@ -89,4 +93,6 @@
 			fielddisplay(obj,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)');
 			fielddisplay(obj,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated');
+			fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method');
+			fielddisplay(obj,'smbref',' reference smb from which deviation is calculated in smb gradients method');
 			fielddisplay(obj,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated');
 			fielddisplay(obj,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated');
@@ -117,4 +123,6 @@
 			if obj.issmbgradients,
 				WriteData(fid,'object',obj,'fieldname','hc','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','href','format','DoubleMat','mattype',1);
+				WriteData(fid,'object',obj,'fieldname','smbref','format','DoubleMat','mattype',1);
 				WriteData(fid,'object',obj,'fieldname','smb_pos_max','format','DoubleMat','mattype',1);
 				WriteData(fid,'object',obj,'fieldname','smb_pos_min','format','DoubleMat','mattype',1);
Index: /issm/trunk/src/m/classes/surfaceforcings.py
===================================================================
--- /issm/trunk/src/m/classes/surfaceforcings.py	(revision 13974)
+++ /issm/trunk/src/m/classes/surfaceforcings.py	(revision 13975)
@@ -22,4 +22,6 @@
 		self.isdelta18o = 0
 		self.hc = float('NaN')
+		self.href = float('NaN')
+		self.smbref = float('NaN')
 		self.smb_pos_max = float('NaN')
 		self.smb_pos_min = float('NaN')
@@ -56,4 +58,6 @@
 		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,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method'))
+		string="%s\n%s"%(string,fielddisplay(self,'smbref',' reference smb from which deviation is calculated in smb gradients method'))
 		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'))
@@ -94,4 +98,6 @@
 			elif self.issmbgradients:
 				md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.href','forcing',1,'NaN',1)
+				md = checkfield(md,'surfaceforcings.smbref','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)
@@ -130,4 +136,6 @@
 		if self.issmbgradients:
 			WriteData(fid,'object',self,'fieldname','hc','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','href','format','DoubleMat','mattype',1)
+			WriteData(fid,'object',self,'fieldname','smbref','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'fieldname','smb_pos_max','format','DoubleMat','mattype',1)
 			WriteData(fid,'object',self,'fieldname','smb_pos_min','format','DoubleMat','mattype',1)
Index: /issm/trunk/src/m/classes/thermal.m
===================================================================
--- /issm/trunk/src/m/classes/thermal.m	(revision 13974)
+++ /issm/trunk/src/m/classes/thermal.m	(revision 13975)
@@ -47,6 +47,8 @@
 			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');
+			if (ismember(EnthalpyAnalysisEnum(),analyses) & (md.thermal.isenthalpy | solution==EnthalpySolutionEnum()) & md.mesh.dimension==3),
+				pos=find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN);
+				replicate=repmat(md.geometry.surface-md.mesh.z,1,size(md.thermal.spctemperature,2));
+				md = checkfield(md,'thermal.spctemperature(find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN))','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate(pos),'message','spctemperature should be below the adjusted melting point');
 				md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0 1]);
 			end
Index: /issm/trunk/src/m/classes/thermal.py
===================================================================
--- /issm/trunk/src/m/classes/thermal.py	(revision 13974)
+++ /issm/trunk/src/m/classes/thermal.py	(revision 13975)
@@ -1,3 +1,4 @@
 #module imports
+import numpy
 from fielddisplay import fielddisplay
 from EnumDefinitions import *
@@ -69,6 +70,8 @@
 		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")
+		if EnthalpyAnalysisEnum() in analyses and (md.thermal.isenthalpy or solution==EnthalpySolutionEnum()) and md.mesh.dimension==3:
+			pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
+			replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1)))
+			md = checkfield(md,'thermal.spctemperature[numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices,:])))]','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate[pos],'message',"spctemperature should be below the adjusted melting point")
 			md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0,1])
 
Index: /issm/trunk/src/m/classes/verbose.m
===================================================================
--- /issm/trunk/src/m/classes/verbose.m	(revision 13974)
+++ /issm/trunk/src/m/classes/verbose.m	(revision 13975)
@@ -9,4 +9,5 @@
 %      control     : control method
 %      qmu         : sensitivity analysis
+%      autodiff    : AD analysis
 %
 %   Usage:
@@ -23,11 +24,12 @@
 		% {{{
 		%BEGINFIELDS
-		mprocessor  = false;
-		module      = false;
-		solution    = false;
-		solver      = false;
-		convergence = false;
-		control     = false;
-		qmu         = false;
+		mprocessor=false;
+		module=false;
+		solution=false;
+		solver=false;
+		convergence=false;
+		control=false;
+		qmu=false;
+		autodiff=false;
 		%ENDFIELDS
 		% }}}
@@ -83,4 +85,5 @@
 		if (verbose.control), binary=bitor(binary,32); end
 		if (verbose.qmu), binary=bitor(binary,64); end
+		if (verbose.autodiff), binary=bitor(binary,128); end
 		%ENDVERB2BIN
 
@@ -90,11 +93,12 @@
 
 		%BEGINBIN2VERB
-		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));
+		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
+		if bitand(binary,128), verbose.autodiff=true; else verbose.autodiff=false; end
 		%ENDBIN2VERB
 
@@ -105,5 +109,5 @@
 		end % }}}
 		function disp(verbose) % {{{
-			
+
 		%BEGINDISP
 		disp(sprintf('class ''%s''  = ',class(verbose)));
@@ -115,4 +119,5 @@
 		disp(sprintf('   %15s : %s','control',mat2str(verbose.control)));
 		disp(sprintf('   %15s : %s','qmu',mat2str(verbose.qmu)));
+		disp(sprintf('   %15s : %s','autodiff',mat2str(verbose.autodiff)));
 		%ENDDISP
 
Index: /issm/trunk/src/m/classes/verbose.py
===================================================================
--- /issm/trunk/src/m/classes/verbose.py	(revision 13974)
+++ /issm/trunk/src/m/classes/verbose.py	(revision 13975)
@@ -16,4 +16,5 @@
 	      control     : control method
 	      qmu         : sensitivity analysis
+	      autodiff    : AD analysis
 
 	   Usage:
@@ -36,4 +37,5 @@
 		self.control     = False
 		self.qmu         = False
+		self.autodiff    = False
 		#ENDFIELDS
 
@@ -61,9 +63,26 @@
 			#Cast to logicals
 			listproperties=vars(self)
-			for [fieldname,fieldvalue] in listproperties.iteritems():
+			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 __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)
+		s+="   %15s : %s\n" % ('autodiff',self.autodiff)
+		#ENDDISP
+
+		return s
 	# }}}
 
@@ -86,4 +105,6 @@
 		if self.qmu:
 			binary=binary | 64
+		if self.autodiff:
+			binary=binary | 128
 		#ENDVERB2BIN
 
@@ -94,11 +115,12 @@
 
 		#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)
+		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)
+		self.autodiff   =bool(binary & 128)
 		#ENDBIN2VERB
 	# }}}
@@ -108,22 +130,6 @@
 	# }}}
 
-	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')
 	# }}}
 
-	def marshall(self,fid):    # {{{
-			WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
-	# }}}
-
Index: /issm/trunk/src/m/consistency/ismodelselfconsistent.m
===================================================================
--- /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 13974)
+++ /issm/trunk/src/m/consistency/ismodelselfconsistent.m	(revision 13975)
@@ -28,9 +28,5 @@
 
 	%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
+	md=checkconsistency(md.(field),md,solution,analyses);
 end
 
@@ -46,6 +42,4 @@
 %   Usage:
 %      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
-
-
 
 switch solutiontype,
Index: /issm/trunk/src/m/contrib/bamg/YamsCall.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/bamg/YamsCall.m	(revision 13975)
@@ -53,8 +53,8 @@
 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=[];
Index: /issm/trunk/src/m/contrib/bamg/meshread.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/meshread.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/bamg/meshread.m	(revision 13975)
@@ -1,3 +1,3 @@
-function Struct=meshread(filename);
+function Struct=meshread(filename)
 
 %some checks
Index: /issm/trunk/src/m/contrib/bamg/yams.m
===================================================================
--- /issm/trunk/src/m/contrib/bamg/yams.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/bamg/yams.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=yams(md,varargin);
+function md=yams(md,varargin)
 %MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
 %
@@ -102,5 +102,5 @@
 
 end
-	
+
 disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
 
Index: /issm/trunk/src/m/contrib/gslib/gamv.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/gamv.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/gslib/gamv.m	(revision 13975)
@@ -1,3 +1,3 @@
-function output = gamv(x,y,data,varargin);
+function output = gamv(x,y,data,varargin)
 %GAMV - use gslib for Kriging
 %
Index: /issm/trunk/src/m/contrib/gslib/gslib.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/gslib/gslib.m	(revision 13975)
@@ -1,3 +1,3 @@
-function output = gslib(x,y,data,varargin);
+function output = gslib(x,y,data,varargin)
 %GSLIB - use gslib for Kriging
 %
Index: /issm/trunk/src/m/contrib/gslib/pkriging.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/gslib/pkriging.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
+function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin)
 %PKRIGING - parallel Kriging
 %
Index: /issm/trunk/src/m/contrib/gslib/varmap.m
===================================================================
--- /issm/trunk/src/m/contrib/gslib/varmap.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/gslib/varmap.m	(revision 13975)
@@ -1,3 +1,3 @@
-function output = varmap(x,y,data,varargin);
+function output = varmap(x,y,data,varargin)
 %VARMAP - use gslib for Kriging
 %
Index: /issm/trunk/src/m/contrib/hack/tres.m
===================================================================
--- /issm/trunk/src/m/contrib/hack/tres.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/hack/tres.m	(revision 13975)
@@ -22,13 +22,7 @@
 		md.initialization.pressure=md.results.DiagnosticSolution.Pressure;
 	end
-	if md.rifts.numrifts,
+	if ~isempty(md.rifts.riftstruct),
 		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
Index: /issm/trunk/src/m/contrib/massbalance/outflow.m
===================================================================
--- /issm/trunk/src/m/contrib/massbalance/outflow.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/massbalance/outflow.m	(revision 13975)
@@ -1,3 +1,3 @@
-function flag=outflow(md);
+function flag=outflow(md)
 %OUTFLOW - flag nodes on outflux boundary
 %
Index: /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m
===================================================================
--- /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m	(revision 13974)
+++ /issm/trunk/src/m/contrib/uci/expremovestraightsegments.m	(revision 13975)
@@ -11,8 +11,8 @@
 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)];
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectIndicesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffDependentObjectIndicesEnum()
+%AUTODIFFDEPENDENTOBJECTINDICESENUM - Enum of AutodiffDependentObjectIndices
+%
+%   WARNING: DO NOT 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=AutodiffDependentObjectIndicesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectIndices');
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectNamesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffDependentObjectNamesEnum()
+%AUTODIFFDEPENDENTOBJECTNAMESENUM - Enum of AutodiffDependentObjectNames
+%
+%   WARNING: DO NOT 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=AutodiffDependentObjectNamesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectNames');
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectTypesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffDependentObjectTypesEnum()
+%AUTODIFFDEPENDENTOBJECTTYPESENUM - Enum of AutodiffDependentObjectTypes
+%
+%   WARNING: DO NOT 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=AutodiffDependentObjectTypesEnum()
+
+macro=StringToEnum('AutodiffDependentObjectTypes');
Index: /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffDependentObjectsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffDependentObjectsEnum()
+%AUTODIFFDEPENDENTOBJECTSENUM - Enum of AutodiffDependentObjects
+%
+%   WARNING: DO NOT 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=AutodiffDependentObjectsEnum()
+
+macro=StringToEnum('AutodiffDependentObjects');
Index: sm/trunk/src/m/enum/AutodiffDependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDependentsEnum.m	(revision 13974)
+++ 	(revision )
@@ -1,11 +1,0 @@
-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: /issm/trunk/src/m/enum/AutodiffDriverEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffDriverEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffDriverEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffDriverEnum()
+%AUTODIFFDRIVERENUM - Enum of AutodiffDriver
+%
+%   WARNING: DO NOT 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=AutodiffDriverEnum()
+
+macro=StringToEnum('AutodiffDriver');
Index: /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffFosForwardIndexEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffFosForwardIndexEnum()
+%AUTODIFFFOSFORWARDINDEXENUM - Enum of AutodiffFosForwardIndex
+%
+%   WARNING: DO NOT 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=AutodiffFosForwardIndexEnum()
+
+macro=StringToEnum('AutodiffFosForwardIndex');
Index: sm/trunk/src/m/enum/AutodiffFosForwardOutputEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosForwardOutputEnum.m	(revision 13974)
+++ 	(revision )
@@ -1,11 +1,0 @@
-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/AutodiffFosReverseIndexEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffFosReverseIndexEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffFosReverseIndexEnum()
+%AUTODIFFFOSREVERSEINDEXENUM - Enum of AutodiffFosReverseIndex
+%
+%   WARNING: DO NOT 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=AutodiffFosReverseIndexEnum()
+
+macro=StringToEnum('AutodiffFosReverseIndex');
Index: /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffFovForwardIndicesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffFovForwardIndicesEnum()
+%AUTODIFFFOVFORWARDINDICESENUM - Enum of AutodiffFovForwardIndices
+%
+%   WARNING: DO NOT 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=AutodiffFovForwardIndicesEnum()
+
+macro=StringToEnum('AutodiffFovForwardIndices');
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectNamesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffIndependentObjectNamesEnum()
+%AUTODIFFINDEPENDENTOBJECTNAMESENUM - Enum of AutodiffIndependentObjectNames
+%
+%   WARNING: DO NOT 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=AutodiffIndependentObjectNamesEnum()
+
+macro=StringToEnum('AutodiffIndependentObjectNames');
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectTypesEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffIndependentObjectTypesEnum()
+%AUTODIFFINDEPENDENTOBJECTTYPESENUM - Enum of AutodiffIndependentObjectTypes
+%
+%   WARNING: DO NOT 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=AutodiffIndependentObjectTypesEnum()
+
+macro=StringToEnum('AutodiffIndependentObjectTypes');
Index: /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffIndependentObjectsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffIndependentObjectsEnum()
+%AUTODIFFINDEPENDENTOBJECTSENUM - Enum of AutodiffIndependentObjects
+%
+%   WARNING: DO NOT 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=AutodiffIndependentObjectsEnum()
+
+macro=StringToEnum('AutodiffIndependentObjects');
Index: sm/trunk/src/m/enum/AutodiffIndependentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffIndependentsEnum.m	(revision 13974)
+++ 	(revision )
@@ -1,11 +1,0 @@
-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/AutodiffKeepEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffKeepEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffKeepEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffKeepEnum()
+%AUTODIFFKEEPENUM - Enum of AutodiffKeep
+%
+%   WARNING: DO NOT 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=AutodiffKeepEnum()
+
+macro=StringToEnum('AutodiffKeep');
Index: /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffMassFluxSegmentsPresentEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffMassFluxSegmentsPresentEnum()
+%AUTODIFFMASSFLUXSEGMENTSPRESENTENUM - Enum of AutodiffMassFluxSegmentsPresent
+%
+%   WARNING: DO NOT 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=AutodiffMassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('AutodiffMassFluxSegmentsPresent');
Index: /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffNumDependentObjectsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumDependentObjectsEnum()
+%AUTODIFFNUMDEPENDENTOBJECTSENUM - Enum of AutodiffNumDependentObjects
+%
+%   WARNING: DO NOT 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=AutodiffNumDependentObjectsEnum()
+
+macro=StringToEnum('AutodiffNumDependentObjects');
Index: /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/AutodiffNumIndependentObjectsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=AutodiffNumIndependentObjectsEnum()
+%AUTODIFFNUMINDEPENDENTOBJECTSENUM - Enum of AutodiffNumIndependentObjects
+%
+%   WARNING: DO NOT 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=AutodiffNumIndependentObjectsEnum()
+
+macro=StringToEnum('AutodiffNumIndependentObjects');
Index: /issm/trunk/src/m/enum/DataSetParamEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DataSetParamEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/DataSetParamEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=DataSetParamEnum()
+%DATASETPARAMENUM - Enum of DataSetParam
+%
+%   WARNING: DO NOT 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=DataSetParamEnum()
+
+macro=StringToEnum('DataSetParam');
Index: /issm/trunk/src/m/enum/DependentObjectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/DependentObjectEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/DependentObjectEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=DependentObjectEnum()
+%DEPENDENTOBJECTENUM - Enum of DependentObject
+%
+%   WARNING: DO NOT 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=DependentObjectEnum()
+
+macro=StringToEnum('DependentObject');
Index: /issm/trunk/src/m/enum/EnumDefinitions.py
===================================================================
--- /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 13974)
+++ /issm/trunk/src/m/enum/EnumDefinitions.py	(revision 13975)
@@ -19,14 +19,4 @@
 	return StringToEnum('AutodiffIsautodiff')[0]
 
-def AutodiffDependentsEnum():
-	"""
-	AUTODIFFDEPENDENTSENUM - Enum of AutodiffDependents
-
-	   Usage:
-	      macro=AutodiffDependentsEnum()
-	"""
-
-	return StringToEnum('AutodiffDependents')[0]
-
 def AutodiffNumDependentsEnum():
 	"""
@@ -39,13 +29,53 @@
 	return StringToEnum('AutodiffNumDependents')[0]
 
-def AutodiffIndependentsEnum():
-	"""
-	AUTODIFFINDEPENDENTSENUM - Enum of AutodiffIndependents
-
-	   Usage:
-	      macro=AutodiffIndependentsEnum()
-	"""
-
-	return StringToEnum('AutodiffIndependents')[0]
+def AutodiffNumDependentObjectsEnum():
+	"""
+	AUTODIFFNUMDEPENDENTOBJECTSENUM - Enum of AutodiffNumDependentObjects
+
+	   Usage:
+	      macro=AutodiffNumDependentObjectsEnum()
+	"""
+
+	return StringToEnum('AutodiffNumDependentObjects')[0]
+
+def AutodiffDependentObjectNamesEnum():
+	"""
+	AUTODIFFDEPENDENTOBJECTNAMESENUM - Enum of AutodiffDependentObjectNames
+
+	   Usage:
+	      macro=AutodiffDependentObjectNamesEnum()
+	"""
+
+	return StringToEnum('AutodiffDependentObjectNames')[0]
+
+def AutodiffDependentObjectTypesEnum():
+	"""
+	AUTODIFFDEPENDENTOBJECTTYPESENUM - Enum of AutodiffDependentObjectTypes
+
+	   Usage:
+	      macro=AutodiffDependentObjectTypesEnum()
+	"""
+
+	return StringToEnum('AutodiffDependentObjectTypes')[0]
+
+def AutodiffDependentObjectIndicesEnum():
+	"""
+	AUTODIFFDEPENDENTOBJECTINDICESENUM - Enum of AutodiffDependentObjectIndices
+
+	   Usage:
+	      macro=AutodiffDependentObjectIndicesEnum()
+	"""
+
+	return StringToEnum('AutodiffDependentObjectIndices')[0]
+
+def AutodiffDependentObjectsEnum():
+	"""
+	AUTODIFFDEPENDENTOBJECTSENUM - Enum of AutodiffDependentObjects
+
+	   Usage:
+	      macro=AutodiffDependentObjectsEnum()
+	"""
+
+	return StringToEnum('AutodiffDependentObjects')[0]
 
 def AutodiffNumIndependentsEnum():
@@ -59,4 +89,44 @@
 	return StringToEnum('AutodiffNumIndependents')[0]
 
+def AutodiffNumIndependentObjectsEnum():
+	"""
+	AUTODIFFNUMINDEPENDENTOBJECTSENUM - Enum of AutodiffNumIndependentObjects
+
+	   Usage:
+	      macro=AutodiffNumIndependentObjectsEnum()
+	"""
+
+	return StringToEnum('AutodiffNumIndependentObjects')[0]
+
+def AutodiffIndependentObjectNamesEnum():
+	"""
+	AUTODIFFINDEPENDENTOBJECTNAMESENUM - Enum of AutodiffIndependentObjectNames
+
+	   Usage:
+	      macro=AutodiffIndependentObjectNamesEnum()
+	"""
+
+	return StringToEnum('AutodiffIndependentObjectNames')[0]
+
+def AutodiffIndependentObjectTypesEnum():
+	"""
+	AUTODIFFINDEPENDENTOBJECTTYPESENUM - Enum of AutodiffIndependentObjectTypes
+
+	   Usage:
+	      macro=AutodiffIndependentObjectTypesEnum()
+	"""
+
+	return StringToEnum('AutodiffIndependentObjectTypes')[0]
+
+def AutodiffIndependentObjectsEnum():
+	"""
+	AUTODIFFINDEPENDENTOBJECTSENUM - Enum of AutodiffIndependentObjects
+
+	   Usage:
+	      macro=AutodiffIndependentObjectsEnum()
+	"""
+
+	return StringToEnum('AutodiffIndependentObjects')[0]
+
 def AutodiffJacobianEnum():
 	"""
@@ -79,13 +149,63 @@
 	return StringToEnum('AutodiffXp')[0]
 
-def AutodiffFosForwardOutputEnum():
-	"""
-	AUTODIFFFOSFORWARDOUTPUTENUM - Enum of AutodiffFosForwardOutput
-
-	   Usage:
-	      macro=AutodiffFosForwardOutputEnum()
-	"""
-
-	return StringToEnum('AutodiffFosForwardOutput')[0]
+def AutodiffDriverEnum():
+	"""
+	AUTODIFFDRIVERENUM - Enum of AutodiffDriver
+
+	   Usage:
+	      macro=AutodiffDriverEnum()
+	"""
+
+	return StringToEnum('AutodiffDriver')[0]
+
+def AutodiffFosForwardIndexEnum():
+	"""
+	AUTODIFFFOSFORWARDINDEXENUM - Enum of AutodiffFosForwardIndex
+
+	   Usage:
+	      macro=AutodiffFosForwardIndexEnum()
+	"""
+
+	return StringToEnum('AutodiffFosForwardIndex')[0]
+
+def AutodiffFovForwardIndicesEnum():
+	"""
+	AUTODIFFFOVFORWARDINDICESENUM - Enum of AutodiffFovForwardIndices
+
+	   Usage:
+	      macro=AutodiffFovForwardIndicesEnum()
+	"""
+
+	return StringToEnum('AutodiffFovForwardIndices')[0]
+
+def AutodiffFosReverseIndexEnum():
+	"""
+	AUTODIFFFOSREVERSEINDEXENUM - Enum of AutodiffFosReverseIndex
+
+	   Usage:
+	      macro=AutodiffFosReverseIndexEnum()
+	"""
+
+	return StringToEnum('AutodiffFosReverseIndex')[0]
+
+def AutodiffMassFluxSegmentsPresentEnum():
+	"""
+	AUTODIFFMASSFLUXSEGMENTSPRESENTENUM - Enum of AutodiffMassFluxSegmentsPresent
+
+	   Usage:
+	      macro=AutodiffMassFluxSegmentsPresentEnum()
+	"""
+
+	return StringToEnum('AutodiffMassFluxSegmentsPresent')[0]
+
+def AutodiffKeepEnum():
+	"""
+	AUTODIFFKEEPENUM - Enum of AutodiffKeep
+
+	   Usage:
+	      macro=AutodiffKeepEnum()
+	"""
+
+	return StringToEnum('AutodiffKeep')[0]
 
 def BalancethicknessSpcthicknessEnum():
@@ -199,4 +319,14 @@
 	return StringToEnum('ConstantsYts')[0]
 
+def DependentObjectEnum():
+	"""
+	DEPENDENTOBJECTENUM - Enum of DependentObject
+
+	   Usage:
+	      macro=DependentObjectEnum()
+	"""
+
+	return StringToEnum('DependentObject')[0]
+
 def DiagnosticAbstolEnum():
 	"""
@@ -589,4 +719,14 @@
 	return StringToEnum('HydrologyStabilization')[0]
 
+def IndependentObjectEnum():
+	"""
+	INDEPENDENTOBJECTENUM - Enum of IndependentObject
+
+	   Usage:
+	      macro=IndependentObjectEnum()
+	"""
+
+	return StringToEnum('IndependentObject')[0]
+
 def InversionControlParametersEnum():
 	"""
@@ -1319,4 +1459,24 @@
 	return StringToEnum('PrognosticVertexPairing')[0]
 
+def PrognosticNumRequestedOutputsEnum():
+	"""
+	PROGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of PrognosticNumRequestedOutputs
+
+	   Usage:
+	      macro=PrognosticNumRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('PrognosticNumRequestedOutputs')[0]
+
+def PrognosticRequestedOutputsEnum():
+	"""
+	PROGNOSTICREQUESTEDOUTPUTSENUM - Enum of PrognosticRequestedOutputs
+
+	   Usage:
+	      macro=PrognosticRequestedOutputsEnum()
+	"""
+
+	return StringToEnum('PrognosticRequestedOutputs')[0]
+
 def QmuIsdakotaEnum():
 	"""
@@ -1329,13 +1489,33 @@
 	return StringToEnum('QmuIsdakota')[0]
 
-def QmuMassFluxSegmentsEnum():
-	"""
-	QMUMASSFLUXSEGMENTSENUM - Enum of QmuMassFluxSegments
-
-	   Usage:
-	      macro=QmuMassFluxSegmentsEnum()
-	"""
-
-	return StringToEnum('QmuMassFluxSegments')[0]
+def MassFluxSegmentsEnum():
+	"""
+	MASSFLUXSEGMENTSENUM - Enum of MassFluxSegments
+
+	   Usage:
+	      macro=MassFluxSegmentsEnum()
+	"""
+
+	return StringToEnum('MassFluxSegments')[0]
+
+def MassFluxSegmentsPresentEnum():
+	"""
+	MASSFLUXSEGMENTSPRESENTENUM - Enum of MassFluxSegmentsPresent
+
+	   Usage:
+	      macro=MassFluxSegmentsPresentEnum()
+	"""
+
+	return StringToEnum('MassFluxSegmentsPresent')[0]
+
+def QmuMassFluxSegmentsPresentEnum():
+	"""
+	QMUMASSFLUXSEGMENTSPRESENTENUM - Enum of QmuMassFluxSegmentsPresent
+
+	   Usage:
+	      macro=QmuMassFluxSegmentsPresentEnum()
+	"""
+
+	return StringToEnum('QmuMassFluxSegmentsPresent')[0]
 
 def QmuNumberofpartitionsEnum():
@@ -1679,4 +1859,24 @@
 	return StringToEnum('SurfaceforcingsHc')[0]
 
+def SurfaceforcingsHrefEnum():
+	"""
+	SURFACEFORCINGSHREFENUM - Enum of SurfaceforcingsHref
+
+	   Usage:
+	      macro=SurfaceforcingsHrefEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsHref')[0]
+
+def SurfaceforcingsSmbrefEnum():
+	"""
+	SURFACEFORCINGSSMBREFENUM - Enum of SurfaceforcingsSmbref
+
+	   Usage:
+	      macro=SurfaceforcingsSmbrefEnum()
+	"""
+
+	return StringToEnum('SurfaceforcingsSmbref')[0]
+
 def SurfaceforcingsSmbPosMaxEnum():
 	"""
@@ -2539,4 +2739,14 @@
 	return StringToEnum('DoubleInput')[0]
 
+def DataSetParamEnum():
+	"""
+	DATASETPARAMENUM - Enum of DataSetParam
+
+	   Usage:
+	      macro=DataSetParamEnum()
+	"""
+
+	return StringToEnum('DataSetParam')[0]
+
 def DoubleMatArrayParamEnum():
 	"""
@@ -2829,4 +3039,14 @@
 	return StringToEnum('PentaP1Input')[0]
 
+def ProfilerEnum():
+	"""
+	PROFILERENUM - Enum of Profiler
+
+	   Usage:
+	      macro=ProfilerEnum()
+	"""
+
+	return StringToEnum('Profiler')[0]
+
 def MatrixParamEnum():
 	"""
@@ -4509,4 +4729,24 @@
 	return StringToEnum('OutputFilePointer')[0]
 
+def OutputFileNameEnum():
+	"""
+	OUTPUTFILENAMEENUM - Enum of OutputFileName
+
+	   Usage:
+	      macro=OutputFileNameEnum()
+	"""
+
+	return StringToEnum('OutputFileName')[0]
+
+def LockFileNameEnum():
+	"""
+	LOCKFILENAMEENUM - Enum of LockFileName
+
+	   Usage:
+	      macro=LockFileNameEnum()
+	"""
+
+	return StringToEnum('LockFileName')[0]
+
 def PetscOptionsAnalysesEnum():
 	"""
@@ -4757,4 +4997,4 @@
 	"""
 
-	return 474
-
+	return 498
+
Index: /issm/trunk/src/m/enum/IndependentObjectEnum.m
===================================================================
--- /issm/trunk/src/m/enum/IndependentObjectEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/IndependentObjectEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=IndependentObjectEnum()
+%INDEPENDENTOBJECTENUM - Enum of IndependentObject
+%
+%   WARNING: DO NOT 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=IndependentObjectEnum()
+
+macro=StringToEnum('IndependentObject');
Index: /issm/trunk/src/m/enum/LockFileNameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/LockFileNameEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/LockFileNameEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=LockFileNameEnum()
+%LOCKFILENAMEENUM - Enum of LockFileName
+%
+%   WARNING: DO NOT 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=LockFileNameEnum()
+
+macro=StringToEnum('LockFileName');
Index: /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/MassFluxSegmentsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=MassFluxSegmentsEnum()
+%MASSFLUXSEGMENTSENUM - Enum of MassFluxSegments
+%
+%   WARNING: DO NOT 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=MassFluxSegmentsEnum()
+
+macro=StringToEnum('MassFluxSegments');
Index: /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/MassFluxSegmentsPresentEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=MassFluxSegmentsPresentEnum()
+%MASSFLUXSEGMENTSPRESENTENUM - Enum of MassFluxSegmentsPresent
+%
+%   WARNING: DO NOT 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=MassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('MassFluxSegmentsPresent');
Index: /issm/trunk/src/m/enum/MaximumNumberOfEnums.m
===================================================================
--- /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 13974)
+++ /issm/trunk/src/m/enum/MaximumNumberOfEnums.m	(revision 13975)
@@ -9,3 +9,3 @@
 %      macro=MaximumNumberOfEnums()
 
-macro=474;
+macro=498;
Index: /issm/trunk/src/m/enum/OutputfilenameEnum.m
===================================================================
--- /issm/trunk/src/m/enum/OutputfilenameEnum.m	(revision 13974)
+++ /issm/trunk/src/m/enum/OutputfilenameEnum.m	(revision 13975)
@@ -1,4 +1,4 @@
-function macro=OutputfilenameEnum()
-%OUTPUTFILENAMEENUM - Enum of Outputfilename
+function macro=OutputFileNameEnum()
+%OUTPUTFILENAMEENUM - Enum of OutputFileName
 %
 %   WARNING: DO NOT MODIFY THIS FILE
@@ -7,5 +7,5 @@
 %
 %   Usage:
-%      macro=OutputfilenameEnum()
+%      macro=OutputFileNameEnum()
 
-macro=StringToEnum('Outputfilename');
+macro=StringToEnum('OutputFileName');
Index: /issm/trunk/src/m/enum/ProfilerEnum.m
===================================================================
--- /issm/trunk/src/m/enum/ProfilerEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/ProfilerEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=ProfilerEnum()
+%PROFILERENUM - Enum of Profiler
+%
+%   WARNING: DO NOT 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=ProfilerEnum()
+
+macro=StringToEnum('Profiler');
Index: /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/PrognosticNumRequestedOutputsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=PrognosticNumRequestedOutputsEnum()
+%PROGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of PrognosticNumRequestedOutputs
+%
+%   WARNING: DO NOT 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=PrognosticNumRequestedOutputsEnum()
+
+macro=StringToEnum('PrognosticNumRequestedOutputs');
Index: /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/PrognosticRequestedOutputsEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=PrognosticRequestedOutputsEnum()
+%PROGNOSTICREQUESTEDOUTPUTSENUM - Enum of PrognosticRequestedOutputs
+%
+%   WARNING: DO NOT 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=PrognosticRequestedOutputsEnum()
+
+macro=StringToEnum('PrognosticRequestedOutputs');
Index: sm/trunk/src/m/enum/QmuMassFluxSegmentsEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMassFluxSegmentsEnum.m	(revision 13974)
+++ 	(revision )
@@ -1,11 +1,0 @@
-function macro=QmuMassFluxSegmentsEnum()
-%QMUMASSFLUXSEGMENTSENUM - Enum of QmuMassFluxSegments
-%
-%   WARNING: DO NOT 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=QmuMassFluxSegmentsEnum()
-
-macro=StringToEnum('QmuMassFluxSegments');
Index: /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m
===================================================================
--- /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/QmuMassFluxSegmentsPresentEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=QmuMassFluxSegmentsPresentEnum()
+%QMUMASSFLUXSEGMENTSPRESENTENUM - Enum of QmuMassFluxSegmentsPresent
+%
+%   WARNING: DO NOT 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=QmuMassFluxSegmentsPresentEnum()
+
+macro=StringToEnum('QmuMassFluxSegmentsPresent');
Index: /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/SurfaceforcingsHrefEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsHrefEnum()
+%SURFACEFORCINGSHREFENUM - Enum of SurfaceforcingsHref
+%
+%   WARNING: DO NOT 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=SurfaceforcingsHrefEnum()
+
+macro=StringToEnum('SurfaceforcingsHref');
Index: /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m
===================================================================
--- /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 13975)
+++ /issm/trunk/src/m/enum/SurfaceforcingsSmbrefEnum.m	(revision 13975)
@@ -0,0 +1,11 @@
+function macro=SurfaceforcingsSmbrefEnum()
+%SURFACEFORCINGSSMBREFENUM - Enum of SurfaceforcingsSmbref
+%
+%   WARNING: DO NOT 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=SurfaceforcingsSmbrefEnum()
+
+macro=StringToEnum('SurfaceforcingsSmbref');
Index: /issm/trunk/src/m/exp/expcoarsen.m
===================================================================
--- /issm/trunk/src/m/exp/expcoarsen.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expcoarsen.m	(revision 13975)
@@ -1,3 +1,3 @@
-function expcoarsen(newfile,oldfile,resolution);
+function expcoarsen(newfile,oldfile,resolution)
 %EXPCOARSEN - coarsen an exp contour
 %
Index: /issm/trunk/src/m/exp/expcontract.m
===================================================================
--- /issm/trunk/src/m/exp/expcontract.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expcontract.m	(revision 13975)
@@ -6,5 +6,4 @@
 %
 %   See also EXPMASTER, EXPDOC
-
 
 contour=expread(oldfile);
Index: /issm/trunk/src/m/exp/expcreatecontour.m
===================================================================
--- /issm/trunk/src/m/exp/expcreatecontour.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expcreatecontour.m	(revision 13975)
@@ -1,3 +1,3 @@
-function expcreatecontour(filename);
+function expcreatecontour(filename)
 %EXPCREATECONTOUR - create a contour from a list of points
 %
@@ -34,3 +34,2 @@
 %write contour using expwrite
 expwrite(a,filename);
-
Index: /issm/trunk/src/m/exp/expcreateprofile.m
===================================================================
--- /issm/trunk/src/m/exp/expcreateprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expcreateprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function expcreateprofile(filename);
+function expcreateprofile(filename)
 %EXPCREATEPROFILE - create an Argus file from a list of points
 %
Index: /issm/trunk/src/m/exp/expexcludeoutliers.m
===================================================================
--- /issm/trunk/src/m/exp/expexcludeoutliers.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expexcludeoutliers.m	(revision 13975)
@@ -7,5 +7,4 @@
 %
 %   See also EXPMASTER, EXPDOC
-
 
 contour=expread(contourname);
Index: /issm/trunk/src/m/exp/expflip.m
===================================================================
--- /issm/trunk/src/m/exp/expflip.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expflip.m	(revision 13975)
@@ -5,8 +5,4 @@
 %
 %
-
-
-
-
 
 a=expread(domainname,1);
Index: /issm/trunk/src/m/exp/expll2xy.m
===================================================================
--- /issm/trunk/src/m/exp/expll2xy.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expll2xy.m	(revision 13975)
@@ -5,5 +5,4 @@
 %      - 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
Index: /issm/trunk/src/m/exp/expread.m
===================================================================
--- /issm/trunk/src/m/exp/expread.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expread.m	(revision 13975)
@@ -1,3 +1,3 @@
-function Struct=expread(filename);
+function Struct=expread(filename)
 %EXPREAD - read a file exp and build a Structure
 %
Index: /issm/trunk/src/m/exp/expswapxy.m
===================================================================
--- /issm/trunk/src/m/exp/expswapxy.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expswapxy.m	(revision 13975)
@@ -6,5 +6,4 @@
 %
 %   See also EXPMASTER, EXPDOC
-
 
 contours=expread(filename,1);
Index: /issm/trunk/src/m/exp/exptool.m
===================================================================
--- /issm/trunk/src/m/exp/exptool.m	(revision 13974)
+++ /issm/trunk/src/m/exp/exptool.m	(revision 13975)
@@ -308,5 +308,4 @@
 			backup{counter,4}=closed;
 
-
 		case 12
 
Index: /issm/trunk/src/m/exp/expwrite.m
===================================================================
--- /issm/trunk/src/m/exp/expwrite.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expwrite.m	(revision 13975)
@@ -1,3 +1,3 @@
-function expwrite(a,filename);
+function expwrite(a,filename)
 %EXPWRITE - write an Argus file from a structure given in input
 %
@@ -20,5 +20,5 @@
 		error('contours x and y coordinates must be of identical size');
 	end
-   
+
 	if isfield(a,'name'),
 		if ~isempty(a(n).name),
@@ -30,5 +30,5 @@
 		fprintf(fid,'%s\n','## Name:');
 	end
-   
+
 	fprintf(fid,'%s\n','## Icon:0');
 	fprintf(fid,'%s\n','# Points Count Value');
Index: /issm/trunk/src/m/exp/expxy2ll.m
===================================================================
--- /issm/trunk/src/m/exp/expxy2ll.m	(revision 13974)
+++ /issm/trunk/src/m/exp/expxy2ll.m	(revision 13975)
@@ -5,5 +5,4 @@
 %      - 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
Index: /issm/trunk/src/m/exp/manipulation/addcontour.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addcontour.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/addcontour.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
 %ADDCONTOUR - add a closed contour
 %
@@ -7,5 +7,5 @@
 %   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
@@ -18,5 +18,5 @@
 
 		[xi,yi] = ginput(1);
-					  
+
 		if ~isempty(xi)
 			x(end+1,1)=xi;
Index: /issm/trunk/src/m/exp/manipulation/addendprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addendprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/addendprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %ADDENDPROFILE - add point at the end of a n existing profile
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/exp/manipulation/addinsideprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addinsideprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/addinsideprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %ADDINSIDEPROFILE - add apoint inside a profile
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/exp/manipulation/addprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/addprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/addprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %ADDPROFILE - add a profile
 %
@@ -7,5 +7,5 @@
 %   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
@@ -18,5 +18,5 @@
 
 		[xi,yi] = ginput(1);
-					  
+
 		if ~isempty(xi)
 			x(end+1,1)=xi;
Index: /issm/trunk/src/m/exp/manipulation/closeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/closeprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/closeprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %CLOSEPROFILE - close one or several profile
 %
@@ -13,5 +13,5 @@
 		return
 	end
-		   
+
 	title('click on the profiles to be closed, RETURN to exit','FontSize',14)
 	hold on
@@ -33,5 +33,5 @@
 
 		[xi,yi] = ginput(1);
-					  
+
 		if ~isempty(xi)
 
Index: /issm/trunk/src/m/exp/manipulation/cutarea.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/cutarea.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/cutarea.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
 %CUTAREA - cut several point of a profile
 %
@@ -10,5 +10,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	hold on
 	loop=1;
Index: /issm/trunk/src/m/exp/manipulation/cutprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/cutprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/cutprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %CUTPROFILE - cut a profile
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/exp/manipulation/mergeprofiles.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/mergeprofiles.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/mergeprofiles.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
 %MERGEPROFILES - merge profiles
 %
Index: /issm/trunk/src/m/exp/manipulation/modifyposition.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/modifyposition.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/modifyposition.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
 %MODIFYPOSITION - modify the prosition of a point of a profile
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/exp/manipulation/orientprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/orientprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/orientprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %ORIENTPROFILE - cahnge profile orientation
 %
@@ -21,7 +21,7 @@
 			return
 		end
-		   
+
 		[xi,yi] = ginput(1);
-					  
+
 		if ~isempty(xi)
 
Index: /issm/trunk/src/m/exp/manipulation/removepoints.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removepoints.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/removepoints.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
 %REMOVEPOINTS - remove a point from a profile
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/exp/manipulation/removeprofile.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removeprofile.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/removeprofile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
 %REMOVEPROFILE - delete a profile
 %
@@ -21,7 +21,7 @@
 			return
 		end
-		   
+
 		[xi,yi] = ginput(1);
-					  
+
 		if ~isempty(xi)
 
Index: /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m
===================================================================
--- /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m	(revision 13974)
+++ /issm/trunk/src/m/exp/manipulation/removeseveralpoints.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
+function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
 %REMOVESEVERALPOINTS - remove several point
 %
@@ -7,5 +7,5 @@
 %   Usage:
 %      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
-		
+
 	%some checks
 	if numprofiles==0
Index: /issm/trunk/src/m/extrusion/DepthAverage.m
===================================================================
--- /issm/trunk/src/m/extrusion/DepthAverage.m	(revision 13974)
+++ /issm/trunk/src/m/extrusion/DepthAverage.m	(revision 13975)
@@ -1,3 +1,3 @@
-function  vector_average=DepthAverage(md,vector);
+function  vector_average=DepthAverage(md,vector)
 %DEPTHAVERAGE - computes depth average of 3d vector, and return value on 2d mesh. 
 %
Index: /issm/trunk/src/m/extrusion/project3d.m
===================================================================
--- /issm/trunk/src/m/extrusion/project3d.m	(revision 13974)
+++ /issm/trunk/src/m/extrusion/project3d.m	(revision 13975)
@@ -1,3 +1,3 @@
-function projected_vector=project3d(md,varargin);
+function projected_vector=project3d(md,varargin)
 %PROJECT3D - vertically project a vector from 2d mesh
 %
Index: /issm/trunk/src/m/geometry/FlagElements.py
===================================================================
--- /issm/trunk/src/m/geometry/FlagElements.py	(revision 13974)
+++ /issm/trunk/src/m/geometry/FlagElements.py	(revision 13975)
@@ -2,5 +2,5 @@
 import os
 #from basinzoom import *
-#from ContourToMesh import *
+from ContourToMesh import *
 from MatlabFuncs import *
 
@@ -41,4 +41,5 @@
 				if len(region)>3 and not strcmp(region[-4:],'.exp'):
 					raise IOError("Error: File 'region' not found!" % region)
+				raise RuntimeError("FlagElements.py calling basinzoom.py is not complete.")
 				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)
@@ -46,10 +47,10 @@
 			else:
 				#ok, flag elements
-				flag=ContourToMesh(md.mesh.elements[:,0:3],md.mesh.x,md.mesh.y,region,'element',1)
+				[flag,dum]=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),region,'element',1)
 
 		if invert:
 			flag=numpy.logical_not(flag)
 
-	elif isinstance(region,numpy.nparray) or isinstance(region,bool):
+	elif isinstance(region,numpy.ndarray) 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.")
Index: /issm/trunk/src/m/geometry/GetAreas.py
===================================================================
--- /issm/trunk/src/m/geometry/GetAreas.py	(revision 13975)
+++ /issm/trunk/src/m/geometry/GetAreas.py	(revision 13975)
@@ -0,0 +1,52 @@
+import numpy
+
+def GetAreas(index,x,y,z=numpy.array([])):
+	"""
+	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=numpy.size(index,axis=0)
+	nods=numpy.size(x)
+
+	#some checks
+	if numpy.size(y)!=nods or (z and numpy.size(z)!=nods):
+		raise TypeError("GetAreas error message: x,y and z do not have the same length.")
+	if numpy.max(index)>nods:
+		raise TypeError("GetAreas error message: index should not have values above %d." % nods)
+	if (not z and numpy.size(index,axis=1)!=3):
+		raise TypeError("GetAreas error message: index should have 3 columns for 2d meshes.")
+	if (z and numpy.size(index,axis=1)!=6):
+		raise TypeError("GetAreas error message: index should have 6 columns for 3d meshes.")
+
+	#initialization
+	areas=numpy.zeros(nels)
+	x1=x[index[:,0].astype(int)-1]
+	x2=x[index[:,1].astype(int)-1]
+	x3=x[index[:,2].astype(int)-1]
+	y1=y[index[:,0].astype(int)-1]
+	y2=y[index[:,1].astype(int)-1]
+	y3=y[index[:,2].astype(int)-1]
+
+	#compute the volume of each element
+	if not z:
+		#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=numpy.mean(z[index[:,3:6].astype(int)-1])-numpy.mean(z[index[:,0:3].astype(int)-1])
+		areas=(0.5*((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)))*thickness
+
+	return areas
+
Index: /issm/trunk/src/m/geometry/SegIntersect.m
===================================================================
--- /issm/trunk/src/m/geometry/SegIntersect.m	(revision 13974)
+++ /issm/trunk/src/m/geometry/SegIntersect.m	(revision 13975)
@@ -49,5 +49,5 @@
 	O1C=O2O1'*O1C;
 	O1D=O2O1'*O1D;
-	
+
 	%test if one point is included in the other segment (->bval=1)
 	if (O1C-O1A)*(O1D-O1A)<0
Index: /issm/trunk/src/m/geometry/SegIntersect.py
===================================================================
--- /issm/trunk/src/m/geometry/SegIntersect.py	(revision 13974)
+++ /issm/trunk/src/m/geometry/SegIntersect.py	(revision 13975)
@@ -1,4 +1,3 @@
 import numpy
-from MatlabFuncs import *
 
 def SegIntersect(seg1,seg2):
@@ -48,5 +47,5 @@
 
 	#if colinear
-	if test1*test2==0 and test3*test4==0 and det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
+	if test1*test2==0 and test3*test4==0 and numpy.linalg.det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
 
 		#projection on the axis O1O2
Index: /issm/trunk/src/m/geometry/isconnected.m
===================================================================
--- /issm/trunk/src/m/geometry/isconnected.m	(revision 13975)
+++ /issm/trunk/src/m/geometry/isconnected.m	(revision 13975)
@@ -0,0 +1,13 @@
+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
Index: /issm/trunk/src/m/interp/PatchToVec.m
===================================================================
--- /issm/trunk/src/m/interp/PatchToVec.m	(revision 13974)
+++ /issm/trunk/src/m/interp/PatchToVec.m	(revision 13975)
@@ -1,3 +1,3 @@
-function vec=PatchToVec(Patch);
+function vec=PatchToVec(Patch)
 %PATCHTOVEC - converts a patch to a vector by averaging over each vertex
 %
Index: /issm/trunk/src/m/interp/SectionValues.m
===================================================================
--- /issm/trunk/src/m/interp/SectionValues.m	(revision 13974)
+++ /issm/trunk/src/m/interp/SectionValues.m	(revision 13975)
@@ -22,5 +22,4 @@
 	y=infile.y;
 end
-
 
 %get the specified resolution
Index: /issm/trunk/src/m/interp/plugvelocities.m
===================================================================
--- /issm/trunk/src/m/interp/plugvelocities.m	(revision 13974)
+++ /issm/trunk/src/m/interp/plugvelocities.m	(revision 13975)
@@ -165,2 +165,3 @@
 	Names.interp='node';
 end
+end
Index: /issm/trunk/src/m/inversions/parametercontrolB.m
===================================================================
--- /issm/trunk/src/m/inversions/parametercontrolB.m	(revision 13974)
+++ /issm/trunk/src/m/inversions/parametercontrolB.m	(revision 13975)
@@ -38,5 +38,4 @@
 	md.inversion.nsteps=nsteps;
 end
-
 
 %cm_min
Index: /issm/trunk/src/m/io/loadmodel.py
===================================================================
--- /issm/trunk/src/m/io/loadmodel.py	(revision 13975)
+++ /issm/trunk/src/m/io/loadmodel.py	(revision 13975)
@@ -0,0 +1,35 @@
+import os.path
+from loadvars import *
+
+def 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)
+	"""
+
+	#check existence
+	if os.path.exists(path):
+		#do nothing
+		pass
+	else:
+		raise IOError("loadmodel error message: file '%s' does not exist" % path)
+
+	try:
+		#recover model on file and name it md
+		struc=loadvars(path)
+
+		name=[key for key in struc.iterkeys()]
+		if len(name)>1:
+			raise IOError("loadmodel error message: file '%s' contains several variables. Only one model should be present." % path)
+
+		md=struc[name[0]]
+		return md
+
+	except Exception as me:
+		print me
+		raise IOError("could not load model '%s'" % path)
+
Index: /issm/trunk/src/m/io/loadvars.py
===================================================================
--- /issm/trunk/src/m/io/loadvars.py	(revision 13975)
+++ /issm/trunk/src/m/io/loadvars.py	(revision 13975)
@@ -0,0 +1,83 @@
+import shelve
+import os.path
+
+def loadvars(*args):
+	"""
+	LOADVARS - function to load variables to a file.
+
+	This function loads one or more variables from a file.  The names of the variables
+	must be supplied.  If more than one variable is specified, it may be done with
+	a list of names or a dictionary of name as keys.  The output type will correspond
+	to the input type.  All the variables in the file may be loaded by specifying only
+	the file name.
+
+	Usage:
+	   a=loadvars('shelve.dat','a')
+	   [a,b]=loadvars('shelve.dat',['a','b'])
+	   nvdict=loadvars('shelve.dat',{'a':None,'b':None})
+	   nvdict=loadvars('shelve.dat')
+
+	"""
+
+	filename=''
+	nvdict={}
+
+	if len(args) >= 1 and isinstance(args[0],(str,unicode)):
+		filename=args[0]
+		if not filename:
+			filename='/tmp/shelve.dat'
+
+	else:
+		raise TypeError("Missing file name.")
+
+	if   len(args) >= 2 and isinstance(args[1],(str,unicode)):    # (filename,name)
+		for name in args[1:]:
+			nvdict[name]=None
+
+	elif len(args) == 2 and isinstance(args[1],list):    # (filename,[names])
+		for name in args[1]:
+			nvdict[name]=None
+
+	elif len(args) == 2 and isinstance(args[1],dict):    # (filename,{names:values})
+		nvdict=args[1]
+
+	elif len(args) == 1:    #  (filename)
+		pass
+
+	else:
+		raise TypeError("Unrecognized input arguments.")
+
+	if os.path.exists(filename):
+		print "Loading variables from file '%s'." % filename
+	else:
+		raise IOError("File '%s' not found." % filename)
+
+	my_shelf = shelve.open(filename,'r') # 'r' for read-only
+
+	if nvdict:
+		for name in nvdict.iterkeys():
+			try:
+				nvdict[name] = my_shelf[name]
+				print "Variable '%s' loaded." % name
+			except KeyError:
+				value = None
+				print "Variable '%s' not found." % name
+
+	else:
+		for name in my_shelf.iterkeys():
+			nvdict[name] = my_shelf[name]
+			print "Variable '%s' loaded." % name
+
+	my_shelf.close()
+
+	if   len(args) >= 2 and isinstance(args[1],(str,unicode)):    # (value)
+		value=[nvdict[name] for name in args[1:]]
+		return value
+
+	elif len(args) == 2 and isinstance(args[1],list):    # ([values])
+		value=[nvdict[name] for name in args[1]]
+		return value
+
+	elif (len(args) == 2 and isinstance(args[1],dict)) or (len(args) == 1):    # ({names:values})
+		return nvdict
+
Index: /issm/trunk/src/m/io/savevars.py
===================================================================
--- /issm/trunk/src/m/io/savevars.py	(revision 13975)
+++ /issm/trunk/src/m/io/savevars.py	(revision 13975)
@@ -0,0 +1,62 @@
+import shelve
+import os.path
+
+def savevars(*args):
+	"""
+	SAVEVARS - function to save variables to a file.
+
+	This function saves one or more variables to a file.  The names of the variables
+	must be supplied.  If more than one variable is specified, it may be done with
+	lists of names and values or a dictionary of name:value pairs.  All the variables
+	in the workspace may be saved by specifying the globals() dictionary, but this
+	may include a lot of extraneous data.
+
+	Usage:
+	   savevars('shelve.dat','a',a)
+	   savevars('shelve.dat',['a','b'],[a,b])
+	   savevars('shelve.dat',{'a':a,'b':b})
+	   savevars('shelve.dat',globals())
+
+	"""
+
+	filename=''
+	nvdict={}
+
+	if len(args) >= 1 and isinstance(args[0],(str,unicode)):
+		filename=args[0]
+		if not filename:
+			filename='/tmp/shelve.dat'
+
+	else:
+		raise TypeError("Missing file name.")
+
+	if   len(args) >= 3 and isinstance(args[1],(str,unicode)):    # (filename,name,value)
+		for i in xrange(1,len(args),2):
+			nvdict[args[i]]=args[i+1]
+
+	elif len(args) == 3 and isinstance(args[1],list) and isinstance(args[2],list):    # (filename,[names],[values])
+		for name,value in zip(args[1],args[2]):
+			nvdict[name]=value
+
+	elif len(args) == 2 and isinstance(args[1],dict):    # (filename,{names:values})
+		nvdict=args[1]
+
+	else:
+		raise TypeError("Unrecognized input arguments.")
+
+	if os.path.exists(filename):
+		print "Shelving variables to existing file '%s'." % filename
+	else:
+		print "Shelving variables to new file '%s'." % filename
+
+	my_shelf = shelve.open(filename,'c') # 'c' for create if not exist, else 'n' for new
+
+	for name,value in nvdict.iteritems():
+		try:
+			my_shelf[name] = value
+			print "Variable '%s' shelved." % name
+		except TypeError:
+			print "Variable '%s' not shelved." % name
+
+	my_shelf.close()
+
Index: /issm/trunk/src/m/kml/edgeadjacency.m
===================================================================
--- /issm/trunk/src/m/kml/edgeadjacency.m	(revision 13974)
+++ /issm/trunk/src/m/kml/edgeadjacency.m	(revision 13975)
@@ -31,5 +31,5 @@
         inode1=elem(i,j);
         inode2=elem(i,mod(j,size(elem,2))+1);
-        
+
 %  loop over the elements containing the first node of the edge to see
 %  if they contain the second node of the edge
Index: /issm/trunk/src/m/kml/exp2kml.m
===================================================================
--- /issm/trunk/src/m/kml/exp2kml.m	(revision 13974)
+++ /issm/trunk/src/m/kml/exp2kml.m	(revision 13975)
@@ -6,8 +6,6 @@
 %
 
-
 %First, read exp file
 domain=expread(input);
-
 
 %then transform: 
Index: /issm/trunk/src/m/kml/kml2exp.m
===================================================================
--- /issm/trunk/src/m/kml/kml2exp.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml2exp.m	(revision 13975)
@@ -6,10 +6,7 @@
 %
 
-
-
-
 %First, read polygon kml file.
 structure=kml_shapefile(input);
-	
+
 %create exp file: 
 domain=struct();
Index: /issm/trunk/src/m/kml/kml_colorstyle.m
===================================================================
--- /issm/trunk/src/m/kml/kml_colorstyle.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_colorstyle.m	(revision 13975)
@@ -18,5 +18,5 @@
         colormode ='normal';
     end
-    
+
     methods
         function [kml]=kml_colorstyle(varargin)
@@ -160,5 +160,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -196,7 +196,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_container.m
===================================================================
--- /issm/trunk/src/m/kml/kml_container.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_container.m	(revision 13975)
@@ -21,5 +21,5 @@
     properties
     end
-    
+
     methods
         function [kml]=kml_container(varargin)
@@ -150,5 +150,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -180,5 +180,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -193,7 +193,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_document.m
===================================================================
--- /issm/trunk/src/m/kml/kml_document.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_document.m	(revision 13975)
@@ -23,5 +23,5 @@
         feature   ={};
     end
-    
+
     methods
         function [kml]=kml_document(varargin)
@@ -162,5 +162,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -202,5 +202,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -230,7 +230,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_feature.m
===================================================================
--- /issm/trunk/src/m/kml/kml_feature.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_feature.m	(revision 13975)
@@ -28,5 +28,5 @@
         style     ={};
     end
-    
+
     methods
         function [kml]=kml_feature(varargin)
@@ -204,5 +204,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -262,5 +262,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -289,7 +289,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_file_swrite.m
===================================================================
--- /issm/trunk/src/m/kml/kml_file_swrite.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_file_swrite.m	(revision 13975)
@@ -130,3 +130,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_file_write.m
===================================================================
--- /issm/trunk/src/m/kml/kml_file_write.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_file_write.m	(revision 13975)
@@ -124,3 +124,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_folder.m
===================================================================
--- /issm/trunk/src/m/kml/kml_folder.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_folder.m	(revision 13975)
@@ -23,5 +23,5 @@
         feature   ={};
     end
-    
+
     methods
         function [kml]=kml_folder(varargin)
@@ -162,5 +162,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -202,5 +202,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -230,7 +230,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_geometry.m
===================================================================
--- /issm/trunk/src/m/kml/kml_geometry.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_geometry.m	(revision 13975)
@@ -14,5 +14,5 @@
     properties
     end
-    
+
     methods
         function [kml]=kml_geometry(varargin)
@@ -143,5 +143,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -173,7 +173,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_linearring.m
===================================================================
--- /issm/trunk/src/m/kml/kml_linearring.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_linearring.m	(revision 13975)
@@ -22,5 +22,5 @@
         coords    =zeros(0,3);
     end
-    
+
     methods
         function [kml]=kml_linearring(varargin)
@@ -165,5 +165,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -203,7 +203,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_linestring.m
===================================================================
--- /issm/trunk/src/m/kml/kml_linestring.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_linestring.m	(revision 13975)
@@ -22,5 +22,5 @@
         coords    =zeros(0,3);
     end
-    
+
     methods
         function [kml]=kml_linestring(varargin)
@@ -165,5 +165,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -203,7 +203,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_linestyle.m
===================================================================
--- /issm/trunk/src/m/kml/kml_linestyle.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_linestyle.m	(revision 13975)
@@ -18,5 +18,5 @@
         width     =1;
     end
-    
+
     methods
         function [kml]=kml_linestyle(varargin)
@@ -143,5 +143,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -170,7 +170,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_mesh_elem.m
===================================================================
--- /issm/trunk/src/m/kml/kml_mesh_elem.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_mesh_elem.m	(revision 13975)
@@ -100,5 +100,5 @@
 cmap=colormap;
 close(hfig)
-    
+
 if exist('edata','var')
     if ~exist('cmin','var')
@@ -175,3 +175,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_mesh_write.m
===================================================================
--- /issm/trunk/src/m/kml/kml_mesh_write.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_mesh_write.m	(revision 13975)
@@ -193,5 +193,5 @@
     cmap=colormap;
     close(hfig)
-    
+
     disp(['Writing ' num2str(size(cmap,1)) ' Matlab colors as KML style templates.']);
     for i=1:size(cmap,1)
@@ -259,3 +259,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_multigeometry.m
===================================================================
--- /issm/trunk/src/m/kml/kml_multigeometry.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_multigeometry.m	(revision 13975)
@@ -16,5 +16,5 @@
         geometry  ={};
     end
-    
+
     methods
         function [kml]=kml_multigeometry(varargin)
@@ -156,5 +156,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -197,5 +197,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -225,7 +225,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_object.m
===================================================================
--- /issm/trunk/src/m/kml/kml_object.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_object.m	(revision 13975)
@@ -15,5 +15,5 @@
         id        ='';
     end
-    
+
     methods
         function [kml]=kml_object(varargin)
@@ -144,5 +144,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -174,7 +174,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_part_edges.m
===================================================================
--- /issm/trunk/src/m/kml/kml_part_edges.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_part_edges.m	(revision 13975)
@@ -101,5 +101,5 @@
 cmap=colormap;
 close(hfig)
-    
+
 if exist('edata','var')
     if ~exist('cmin','var')
@@ -139,5 +139,5 @@
     for k=1:md.qmu.numberofpartitions
 %        disp(['partition k=' int2str(k)])
-        
+
 %  for each partition, find all the included elements and determine the
 %  perimeter (including those shared by another partition)
@@ -154,5 +154,5 @@
         [edgeper,elemper,iloop]=edgeperimeter(elemp,nodeconp,edgeadjp);
         iloop(end+1)=size(edgeper,1)+1;
-        
+
 %  determine the data to be used for the colors (if any)
 
@@ -170,5 +170,5 @@
             end
         end
-        
+
 %  set up the placemark with multigeometry
 
@@ -211,5 +211,5 @@
             lat=[];
             long=[];
-            
+
 %  loop over the element edges on the loop of the partition
 
@@ -241,5 +241,5 @@
                     slast=0;
                     j=j+1;
-                    
+
 %  element not entirely within partition, so figure out boundary
                 else
@@ -327,5 +327,5 @@
                             end
                             nlast=0;
-                            
+
 %  write out midpoint of first side
                             kline.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
@@ -481,3 +481,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_part_elems.m
===================================================================
--- /issm/trunk/src/m/kml/kml_part_elems.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_part_elems.m	(revision 13975)
@@ -101,5 +101,5 @@
 cmap=colormap;
 close(hfig)
-    
+
 if exist('edata','var')
     if ~exist('cmin','var')
@@ -215,3 +215,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_part_flagedges.m
===================================================================
--- /issm/trunk/src/m/kml/kml_part_flagedges.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_part_flagedges.m	(revision 13975)
@@ -108,3 +108,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_partitions.m
===================================================================
--- /issm/trunk/src/m/kml/kml_partitions.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_partitions.m	(revision 13975)
@@ -102,5 +102,5 @@
 cmap=colormap;
 close(hfig)
-    
+
 if exist('edata','var')
     if ~exist('cmin','var')
@@ -140,5 +140,5 @@
     for k=1:md.qmu.numberofpartitions
 %        disp(['partition k=' int2str(k)])
-        
+
 %  for each partition, find all the included elements and determine the
 %  perimeter (including those shared by another partition)
@@ -171,5 +171,5 @@
             end
         end
-        
+
 %  set up the placemark with multigeometry
 
@@ -197,5 +197,5 @@
         kmgeom=kml_multigeometry();
         kmgeom.geometry  ={repmat(kml_polygon(),1,length(iloop)-1)};
-        
+
 %  loop over each loop of the perimeter for the given partition
 
@@ -213,5 +213,5 @@
             lat=[];
             long=[];
-            
+
 %  loop over the element edges on the loop of the partition
 
@@ -243,5 +243,5 @@
                     slast=0;
                     j=j+1;
-                    
+
 %  element not entirely within partition, so figure out boundary
                 else
@@ -329,5 +329,5 @@
                             end
                             nlast=0;
-                            
+
 %  write out midpoint of first side
                             kring.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
@@ -484,3 +484,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/kml_placemark.m
===================================================================
--- /issm/trunk/src/m/kml/kml_placemark.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_placemark.m	(revision 13975)
@@ -23,5 +23,5 @@
         geometry  =kml_geometry.empty();
     end
-    
+
     methods
         function [kml]=kml_placemark(varargin)
@@ -163,5 +163,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -204,5 +204,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -233,7 +233,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_polygon.m
===================================================================
--- /issm/trunk/src/m/kml/kml_polygon.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_polygon.m	(revision 13975)
@@ -24,5 +24,5 @@
         inner     =kml_linearring.empty();
     end
-    
+
     methods
         function [kml]=kml_polygon(varargin)
@@ -183,5 +183,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -234,5 +234,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -266,7 +266,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_polystyle.m
===================================================================
--- /issm/trunk/src/m/kml/kml_polystyle.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_polystyle.m	(revision 13975)
@@ -20,5 +20,5 @@
         outline   =true;
     end
-    
+
     methods
         function [kml]=kml_polystyle(varargin)
@@ -148,5 +148,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -176,7 +176,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_style.m
===================================================================
--- /issm/trunk/src/m/kml/kml_style.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_style.m	(revision 13975)
@@ -30,5 +30,5 @@
         list      =[];
     end
-    
+
     methods
         function [kml]=kml_style(varargin)
@@ -206,5 +206,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -268,5 +268,5 @@
 
         end
-        
+
 %  delete the object
 
@@ -322,7 +322,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_styleselector.m
===================================================================
--- /issm/trunk/src/m/kml/kml_styleselector.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_styleselector.m	(revision 13975)
@@ -14,5 +14,5 @@
     properties
     end
-    
+
     methods
         function [kml]=kml_styleselector(varargin)
@@ -143,5 +143,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -173,7 +173,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_substyle.m
===================================================================
--- /issm/trunk/src/m/kml/kml_substyle.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_substyle.m	(revision 13975)
@@ -14,5 +14,5 @@
     properties
     end
-    
+
     methods
         function [kml]=kml_substyle(varargin)
@@ -143,5 +143,5 @@
 
         end
-        
+
 %  string write the object
 
@@ -173,7 +173,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/kml/kml_unsh_edges.m
===================================================================
--- /issm/trunk/src/m/kml/kml_unsh_edges.m	(revision 13974)
+++ /issm/trunk/src/m/kml/kml_unsh_edges.m	(revision 13975)
@@ -114,3 +114,2 @@
 
 end
-
Index: /issm/trunk/src/m/kml/string_buf.m
===================================================================
--- /issm/trunk/src/m/kml/string_buf.m	(revision 13974)
+++ /issm/trunk/src/m/kml/string_buf.m	(revision 13975)
@@ -173,5 +173,5 @@
 
         end
-        
+
 %  reset the object
 
@@ -183,7 +183,6 @@
 
         end
-        
+
     end
-    
+
 end
-
Index: /issm/trunk/src/m/materials/paterson.m
===================================================================
--- /issm/trunk/src/m/materials/paterson.m	(revision 13974)
+++ /issm/trunk/src/m/materials/paterson.m	(revision 13975)
@@ -2,5 +2,5 @@
 %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). 
+%   rigidity (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
 %
Index: /issm/trunk/src/m/materials/paterson.py
===================================================================
--- /issm/trunk/src/m/materials/paterson.py	(revision 13974)
+++ /issm/trunk/src/m/materials/paterson.py	(revision 13975)
@@ -1,23 +1,22 @@
-from numpy import *
+import numpy
 
 def paterson(temperature):
+	"""
+	PATERSON - figure out the rigidity of ice for a given 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 []
-    
+	   rigidity (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 numpy.any(temperature<0.):
+		raise RuntimeError("input temperature should be in Kelvin (positive)")
+	
 	T = temperature-273.15
+
 	#The routine below is equivalent to:
+
 	# n=3; T=temperature-273;
 	# %From paterson,
@@ -31,19 +30,31 @@
 	# 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)
+	rigidity=numpy.zeros((numpy.size(T,axis=0),1))
+	pos1=numpy.nonzero(T<=-45)
+	rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
+	pos2=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(numpy.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=numpy.nonzero(-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 
+	pos=numpy.nonzero(rigidity<0)
+	rigidity[pos]=1**6 
 
 	return rigidity
Index: /issm/trunk/src/m/mech/basalstress.m
===================================================================
--- /issm/trunk/src/m/mech/basalstress.m	(revision 13974)
+++ /issm/trunk/src/m/mech/basalstress.m	(revision 13975)
@@ -6,5 +6,4 @@
 %
 %   See also: plot_basaldrag
-
 
 %compute exponents
Index: /issm/trunk/src/m/mech/cfl_step.m
===================================================================
--- /issm/trunk/src/m/mech/cfl_step.m	(revision 13974)
+++ /issm/trunk/src/m/mech/cfl_step.m	(revision 13975)
@@ -1,3 +1,3 @@
-function maxtime=cfl_step(md,vx,vy);
+function maxtime=cfl_step(md,vx,vy)
 %CFL_STEP - return the maximum time step for the model in years
 %
Index: /issm/trunk/src/m/mech/mechanicalproperties.m
===================================================================
--- /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 13974)
+++ /issm/trunk/src/m/mech/mechanicalproperties.m	(revision 13975)
@@ -51,11 +51,24 @@
 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);
+
+if isa(md.materials,'matice')
+	location=find(second_inv~=0);
+	nu(location)=B_bar(location)./(second_inv(location).^power(location));
+	location=find(second_inv==0 & power==0);
+	nu(location)=B_bar(location);
+elseif isa(md.materials,'matdamageice')
+	Zinv=md.materials.rheology_Z(index)*summation/3;
+	location=find(second_inv~=0);
+	nu(location)=Zinv(location).*B_bar(location)./(second_inv(location).^power(location));
+	location=find(second_inv==0 & power==0);
+	nu(location)=Zinv(location).*B_bar(location);
+	clear Zinv
+else
+	error(['class of md.materials (' class(md.materials) ') not recognized or not supported']);
+end
 clear B_bar location second_inv power
 
@@ -76,7 +89,16 @@
 	%eigen values and vectors
 	[directions,value]=eig(stress);
+	%sort by absolute value of eigenvalue in descending order
+	[val,idx]=sort(abs(diag(value)),'descend');
+	%re-order eigenvalues and associated vectors 
+	value=value(idx,idx);
+	directions=directions(:,idx);
 	valuesstress(i,:)=[value(1,1) value(2,2)];
 	directionsstress(i,:)=directions(:)';
 	[directions,value]=eig(strain);
+	%same for strainrate
+	[val,idx]=sort(abs(diag(value)),'descend');
+	value=value(idx,idx);
+	directions=directions(:,idx);
 	valuesstrain(i,:)=[value(1,1) value(2,2)];
 	directionsstrain(i,:)=directions(:)';
@@ -89,8 +111,8 @@
 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.principalvalue1=valuesstress(:,1);
+stress.principalaxis1=directionsstress(:,1:2);
+stress.principalvalue2=valuesstress(:,2);
+stress.principalaxis2=directionsstress(:,3:4);
 stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
 md.results.stress=stress;
@@ -100,8 +122,8 @@
 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.principalvalue1=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis1=directionsstrain(:,1:2);
+strainrate.principalvalue2=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
+strainrate.principalaxis2=directionsstrain(:,3:4);
 strainrate.effectivevalue=1/sqrt(2)*sqrt(strainrate.xx.^2+strainrate.yy.^2+2*strainrate.xy.^2);
 md.results.strainrate=strainrate;
@@ -111,8 +133,8 @@
 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.principalvalue1=valuesstress(:,1);
+deviatoricstress.principalaxis1=directionsstress(:,1:2);
+deviatoricstress.principalvalue2=valuesstress(:,2);
+deviatoricstress.principalaxis2=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/mesh/ComputeHessian.m
===================================================================
--- /issm/trunk/src/m/mesh/ComputeHessian.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/ComputeHessian.m	(revision 13975)
@@ -20,5 +20,5 @@
 	error('ComputeHessian error message: the given field size not supported yet');
 end
-if strcmpi(type,'node') & strcmpi(type,'element'),
+if ~strcmpi(type,'node') & ~strcmpi(type,'element'),
 	error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
 end
@@ -28,9 +28,9 @@
 linesize=3*numberofelements;
 
-%get areas and  nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+%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
+%compute weights that hold the volume of all the element holding the node i
 weights=sparse(line,ones(linesize,1),repmat(areas,3,1),numberofnodes,1);
 
Index: /issm/trunk/src/m/mesh/ComputeHessian.py
===================================================================
--- /issm/trunk/src/m/mesh/ComputeHessian.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/ComputeHessian.py	(revision 13975)
@@ -0,0 +1,66 @@
+import numpy
+from GetNodalFunctionsCoeff import *
+from GetAreas import *
+from MatlabFuncs import *
+
+def 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=numpy.size(x)
+	numberofelements=numpy.size(index,axis=0)
+
+	#some checks
+	if numpy.size(field)!=numberofnodes and numpy.size(field)!=numberofelements:
+		raise TypeError("ComputeHessian error message: the given field size not supported yet")
+	if not strcmpi(type,'node') and not strcmpi(type,'element'):
+		raise TypeError("ComputeHessian error message: only 'node' or 'element' type supported yet")
+
+	#initialization
+	line=index.reshape(-1,order='F')
+	linesize=3*numberofelements
+
+	#get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
+	[alpha,beta,dum]=GetNodalFunctionsCoeff(index,x,y)
+	areas=GetAreas(index,x,y)
+
+	#compute weights that hold the volume of all the element holding the node i
+	weights=sparse(line,numpy.ones((linesize,1)),numpy.tile(areas.reshape(-1,1),(3,1)),numberofnodes,1)
+
+	#compute field on nodes if on elements
+	if numpy.size(field,axis=0)==numberofelements:
+		field=sparse(line,numpy.ones((linesize,1)),numpy.tile(areas*field,(3,1)),numberofnodes,1)/weights
+
+	#Compute gradient for each element
+	grad_elx=numpy.sum(field[index.astype(int)-1,0]*alpha,axis=1) 
+	grad_ely=numpy.sum(field[index.astype(int)-1,0]*beta,axis=1)
+
+	#Compute gradient for each node (average of the elements around)
+	gradx=sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*grad_elx).reshape(-1,1),(3,1)),numberofnodes,1)
+	grady=sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*grad_ely).reshape(-1,1),(3,1)),numberofnodes,1)
+	gradx=gradx/weights
+	grady=grady/weights
+
+	#Compute hessian for each element
+	hessian=numpy.hstack((numpy.sum(gradx[index.astype(int)-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index.astype(int)-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index.astype(int)-1,0]*beta,axis=1).reshape(-1,1)))
+
+	if strcmpi(type,'node'):
+		#Compute Hessian on the nodes (average of the elements around)
+		hessian=numpy.hstack((sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,0]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
+			sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,1]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
+			sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,2]).reshape(-1,1),(3,1)),numberofnodes,1)/weights ))
+
+	return hessian
+
Index: /issm/trunk/src/m/mesh/ComputeMetric.m
===================================================================
--- /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/ComputeMetric.m	(revision 13975)
@@ -9,8 +9,8 @@
 %      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)]
+%first, find the eigen values of each 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));
+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);
@@ -18,17 +18,17 @@
 
 %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);
+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;
+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;
+v1x(pos3)=1.; v1y(pos3)=0.;
+v2x(pos3)=0.; v2y(pos3)=1.;
 
 %Compute new metric (for each node M=V*Lambda*V^-1)
@@ -38,9 +38,9 @@
 
 %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);
+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);
+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)
@@ -54,6 +54,6 @@
 		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);
+		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);
Index: /issm/trunk/src/m/mesh/ComputeMetric.py
===================================================================
--- /issm/trunk/src/m/mesh/ComputeMetric.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/ComputeMetric.py	(revision 13975)
@@ -0,0 +1,74 @@
+import numpy
+
+def 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 each line of H=[hessian(i,1) hessian(i,2); hessian(i,2) hessian(i,3)]
+	a=hessian[:,0]
+	b=hessian[:,1]
+	d=hessian[:,2]
+	lambda1=0.5*((a+d)+numpy.sqrt(4.*b**2+(a-d)**2))
+	lambda2=0.5*((a+d)-numpy.sqrt(4.*b**2+(a-d)**2))
+	pos1=numpy.nonzero(lambda1==0)[0]
+	pos2=numpy.nonzero(lambda2==0)[0]
+	pos3=numpy.nonzero(numpy.logical_and(b==0,lambda1==lambda2))[0]
+
+	#Modify the eigen values to control the shape of the elements
+	lambda1=numpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
+	lambda2=numpy.minimum(numpy.maximum(numpy.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
+
+	#compute eigen vectors
+	norm1=numpy.sqrt(8.*b**2+2.*(d-a)**2+2.*(d-a)*numpy.sqrt((a-d)**2+4.*b**2))
+	v1x=2.*b/norm1
+	v1y=((d-a)+numpy.sqrt((a-d)**2+4.*b**2))/norm1
+	norm2=numpy.sqrt(8.*b**2+2.*(d-a)**2-2.*(d-a)*numpy.sqrt((a-d)**2+4.*b**2))
+	v2x=2.*b/norm2
+	v2y=((d-a)-numpy.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=numpy.hstack((((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v2y*v1x-lambda2*v1y*v2x)).reshape(-1,1), \
+		                 ((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v1y*v2y-lambda2*v1y*v2y)).reshape(-1,1), \
+		                 ((v1x*v2y-v1y*v2x)**(-1)*(-lambda1*v2x*v1y+lambda2*v1x*v2y)).reshape(-1,1)))
+
+	#some corrections for 0 eigen values
+	metric[pos1,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos1),1))
+	metric[pos2,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos2),1))
+
+	#take care of water elements
+	metric[pos ,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos ),1))
+
+	#take care of NaNs if any (use Numpy eig in a loop)
+	pos=numpy.nonzero(numpy.isnan(metric))[0]
+	if pos:
+		print(" %i NaN found in the metric. Use Numpy routine..." % numpy.size(pos))
+		for posi in pos:
+			H=numpy.array([[hessian[posi,0],hessian[posi,1]],[hessian[posi,1],hessian[posi,2]]])
+			[v,u]=numpy.linalg.eig(H)
+			v=numpy.diag(v)
+			lambda1=v[0,0]
+			lambda2=v[1,1]
+			v[0,0]=numpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
+			v[1,1]=numpy.minimum(numpy.maximum(numpy.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
+
+			metricTria=numpy.dot(numpy.dot(u,v),numpy.linalg.inv(u))
+			metric[posi,:]=numpy.array([metricTria[0,0],metricTria[0,1],metricTria[1,1]])
+
+	if numpy.any(numpy.isnan(metric)):
+		raise RunTimeError("ComputeMetric error message: NaN in the metric despite our efforts...")
+
+	return metric
+
Index: /issm/trunk/src/m/mesh/ElementsFromEdge.m
===================================================================
--- /issm/trunk/src/m/mesh/ElementsFromEdge.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/ElementsFromEdge.m	(revision 13975)
@@ -1,15 +1,15 @@
-function edgeelements=ElementsFromEdge(elements,A,B) 
+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) 
+%   Usage: edgeelements=ElementsFromEdge(elements,A,B) 
 %
-% Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
+%   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 ));
+	(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/ElementsFromEdge.py
===================================================================
--- /issm/trunk/src/m/mesh/ElementsFromEdge.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/ElementsFromEdge.py	(revision 13975)
@@ -0,0 +1,27 @@
+import numpy
+
+def 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=numpy.nonzero(\
+		numpy.logical_or( \
+		numpy.logical_or( \
+		numpy.logical_or(numpy.logical_and(elements[:,0]==A,elements[:,1]==B), \
+						 numpy.logical_and(elements[:,0]==A,elements[:,2]==B)) \
+		, \
+		numpy.logical_or(numpy.logical_and(elements[:,1]==A,elements[:,2]==B), \
+						 numpy.logical_and(elements[:,1]==A,elements[:,0]==B)) \
+		), \
+		numpy.logical_or(numpy.logical_and(elements[:,2]==A,elements[:,0]==B), \
+						 numpy.logical_and(elements[:,2]==A,elements[:,1]==B)) \
+		))[0]+1
+
+	return edgeelements
+
Index: /issm/trunk/src/m/mesh/FixMesh.m
===================================================================
--- /issm/trunk/src/m/mesh/FixMesh.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/FixMesh.m	(revision 13975)
@@ -32,5 +32,5 @@
 	%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;
Index: /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.py
===================================================================
--- /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/GetNodalFunctionsCoeff.py	(revision 13975)
@@ -0,0 +1,58 @@
+import numpy
+
+def 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.reshape(-1)
+	y=y.reshape(-1)
+
+	#get nels and nods
+	nels=numpy.size(index,axis=0)
+	nods=numpy.size(x)
+
+	#some checks
+	if numpy.size(y)!=nods:
+		raise TypeError("GetNodalFunctionsCoeff error message: x and y do not have the same length.")
+	if numpy.max(index)>nods:
+		raise TypeError("GetNodalFunctionsCoeff error message: index should not have values above %d." % nods)
+	if numpy.size(index,axis=1)!=3:
+		raise TypeError("GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.")
+
+	#initialize output
+	alpha=numpy.zeros((nels,3))
+	beta=numpy.zeros((nels,3))
+
+	#compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
+	x1=x[index[:,0].astype(int)-1]
+	x2=x[index[:,1].astype(int)-1]
+	x3=x[index[:,2].astype(int)-1]
+	y1=y[index[:,0].astype(int)-1]
+	y2=y[index[:,1].astype(int)-1]
+	y3=y[index[:,2].astype(int)-1]
+	invdet=1./(x1*(y2-y3)-x2*(y1-y3)+x3*(y1-y2))
+
+	#get alpha and beta
+	alpha=numpy.hstack(((invdet*(y2-y3)).reshape(-1,1),(invdet*(y3-y1)).reshape(-1,1),(invdet*(y1-y2)).reshape(-1,1)))
+	beta =numpy.hstack(((invdet*(x3-x2)).reshape(-1,1),(invdet*(x1-x3)).reshape(-1,1),(invdet*(x2-x1)).reshape(-1,1)))
+
+	#get gamma if requested
+	gamma=numpy.zeros((nels,3))
+	gamma=numpy.hstack(((invdet*(x2*y3-x3*y2)).reshape(-1,1),(invdet*(y1*x3-y3*x1)).reshape(-1,1),(invdet*(x1*y2-x2*y1)).reshape(-1,1)))
+
+	return alpha,beta,gamma
+
Index: /issm/trunk/src/m/mesh/MeshQuality.m
===================================================================
--- /issm/trunk/src/m/mesh/MeshQuality.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/MeshQuality.m	(revision 13975)
@@ -1,3 +1,3 @@
-function quality=MeshQuality(md,epsilon,hmin,hmax);
+function quality=MeshQuality(md,epsilon,hmin,hmax)
 %MESHQUALITY - compute mesh quality
 %
Index: /issm/trunk/src/m/mesh/NodeInElement.m
===================================================================
--- /issm/trunk/src/m/mesh/NodeInElement.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/NodeInElement.m	(revision 13975)
@@ -1,3 +1,3 @@
-function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity);
+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.
 %
@@ -25,5 +25,5 @@
 	x0=newx(i);
 	y0=newy(i);
-	
+
 	%first area coordinate
 	area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
@@ -32,5 +32,5 @@
 	%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));
Index: /issm/trunk/src/m/mesh/bamg.m
===================================================================
--- /issm/trunk/src/m/mesh/bamg.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/bamg.m	(revision 13975)
@@ -55,6 +55,6 @@
 %initialize the structures required as input of Bamg
 bamg_options=struct();
-bamg_geometry=bamggeom;
-bamg_mesh=bamgmesh;
+bamg_geometry=bamggeom();
+bamg_mesh=bamgmesh();
 
 % Bamg Geometry parameters {{{
@@ -63,5 +63,5 @@
 	%Check that file exists
 	domainfile=getfieldvalue(options,'domain');
-	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found ']); end
+	if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found']); end
 	domain=expread(domainfile);
 
@@ -79,5 +79,5 @@
 			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');
+				error('bamg error message: All holes should be strictly inside the principal domain');
 			end
 		end
@@ -86,5 +86,5 @@
 		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)]];
+		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
 
@@ -105,8 +105,8 @@
 		for i=1:length(rift),
 
-			%detect wether all points of the rift are inside the domain
+			%detect whether 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'),
+				error('one rift has all its points outside of the domain outline'),
 
 			elseif any(~flags),
@@ -114,5 +114,5 @@
 				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)
+				%check that only one point is outside (for now)
 				if sum(~flags)~=1,
 					error('bamg error message: only one point outside of the domain is supported yet');
@@ -137,5 +137,5 @@
 						%Get position of the two nodes of the edge in domain
 						i1=j;
-						i2=mod(j+1,domain(1).nods);
+						i2=j+1;
 
 						%rift is crossing edge [i1 i2] of the domain
@@ -152,5 +152,5 @@
 							disp('moving tip-domain intersection point');
 
-							%Get position of the closest point
+							%Get position of the closer point
 							if tipdis(1)>tipdis(2),
 								pos=i2;
@@ -160,10 +160,10 @@
 
 							%This point is only in Vertices (number pos).
-							%OK, no we can add our own rift
+							%OK, now 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)]];
+								[transpose(count+1:count+nods-1) transpose(count+2:count+nods)  (1+i)*ones(nods-1,1)]];
 							count=count+nods;
 
@@ -175,18 +175,18 @@
 							count=count+1;
 
-							%Decompose the crossing edge in 2 subedges
+							%Decompose the crossing edge into 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
+							if isempty(pos) error('bamg error message: a problem occurred...'); 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) 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
+							%OK, now 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)]];
+								[transpose(count+1:count+nods-1) transpose(count+2:count+nods)  (1+i)*ones(nods-1,1)]];
 							count=count+nods;
 
@@ -198,5 +198,5 @@
 				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)]];
+				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
@@ -210,10 +210,10 @@
 		track=getfieldvalue(options,'tracks');
 		if all(ischar(track)),
-			A=expread(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
+		if(size(track,2)==2), track=[track 3.*ones(size(track,1),1)]; end
 
 		%only keep those inside
@@ -224,5 +224,5 @@
 		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)]];
+		bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose(count+2:count+nods)  3.*ones(nods-1,1)]];
 
 		%update counter
@@ -235,6 +235,6 @@
 		%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
-	
+		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);
@@ -276,7 +276,7 @@
 % 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.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);
@@ -284,13 +284,13 @@
 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.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.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10.);
 bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
-bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10);
+bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10.);
 bamg_options.metric=getfieldvalue(options,'metric',[]);
 bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
@@ -298,5 +298,5 @@
 bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
 bamg_options.omega=getfieldvalue(options,'omega',1.8);
-bamg_options.power=getfieldvalue(options,'power',1);
+bamg_options.power=getfieldvalue(options,'power',1.);
 bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
 bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
@@ -334,6 +334,4 @@
 
 %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)');
@@ -341,5 +339,5 @@
 end 
 
-function geom=processgeometry(geom,tol,outline); % {{{
+function geom=processgeometry(geom,tol,outline) % {{{
 
 %Deal with edges
Index: /issm/trunk/src/m/mesh/bamg.py
===================================================================
--- /issm/trunk/src/m/mesh/bamg.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/bamg.py	(revision 13975)
@@ -0,0 +1,488 @@
+import os.path
+import numpy
+from collections import OrderedDict
+from pairoptions import *
+from bamggeom import *
+from bamgmesh import *
+from expread import *
+from expwrite import *
+from SegIntersect import *
+from MatlabFuncs import *
+from BamgMesher import *
+from ContourToNodes import *
+
+def bamg(md,*args):
+	"""
+	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(*args)
+#	options=deleteduplicates(options,1);
+
+	#initialize the structures required as input of Bamg
+	bamg_options=OrderedDict()
+	bamg_geometry=bamggeom()
+	bamg_mesh=bamgmesh()
+
+	# Bamg Geometry parameters {{{
+	if options.exist('domain'):
+
+		#Check that file exists
+		domainfile=options.getfieldvalue('domain')
+		if not os.path.exists(domainfile):
+			raise IOError("bamg error message: file '%s' not found" % domainfile)
+		domain=expread(domainfile)
+
+		#Build geometry 
+		count=0
+		for i,domaini in enumerate(domain):
+
+			#Check that the domain is closed
+			if (domaini['x'][0]!=domaini['x'][-1] or domaini['y'][0]!=domaini['y'][-1]):
+				raise RuntimeError("bamg error message: all contours provided in ''domain'' should be closed")
+
+			#Checks that all holes are INSIDE the principle domain outline
+			if i:
+				flags=ContourToNodes(domaini['x'].reshape(-1,1),domaini['y'].reshape(-1,1),domainfile,0)
+				if numpy.any(numpy.logical_not(flags)):
+					raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
+
+			#Add all points to bamg_geometry
+			nods=domaini['nods']-1    #the domain are closed 0=end
+			bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((domaini['x'][0:nods].reshape(-1,1),domaini['y'][0:nods].reshape(-1,1),numpy.ones((nods,1))))))
+			bamg_geometry.Edges   =numpy.vstack((bamg_geometry.Edges,   numpy.hstack((numpy.arange(count+1,count+nods+1).reshape(-1,1),numpy.hstack((numpy.arange(count+2,count+nods+1),count+1)).reshape(-1,1),1.*numpy.ones((nods,1))))))
+			if i:
+				bamg_geometry.SubDomains=numpy.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
+
+			#update counter
+			count+=nods
+
+		#take care of rifts
+		if options.exist('rifts'):
+
+			#Check that file exists
+			riftfile=options.getfieldvalue('rifts')
+			if not os.path.exists(riftfile):
+				raise IOError("bamg error message: file '%s' not found" % riftfile)
+			rift=expread(riftfile)
+
+			for i,rifti in enumerate(rift):
+
+				#detect whether all points of the rift are inside the domain
+				flags=ContourToNodes(rifti['x'].reshape(-1,1),rifti['y'].reshape(-1,1),domain[0],0)
+				if numpy.all(numpy.logical_not(flags)):
+					raise RuntimeError("one rift has all its points outside of the domain outline")
+
+				elif numpy.any(numpy.logical_not(flags)):
+					#We LOTS of work to do
+					print "Rift tip outside of or on the domain has been detected and is being processed..."
+
+					#check that only one point is outside (for now)
+					if numpy.sum(numpy.logical_not(flags).astype(int))!=1:
+						raise RuntimeError("bamg error message: only one point outside of the domain is supported yet")
+
+					#Move tip outside to the first position
+					if   not flags[0]:
+						#OK, first point is outside (do nothing),
+						pass
+					elif not flags[-1]:
+						rifti['x']=numpy.flipud(rifti['x'])
+						rifti['y']=numpy.flipud(rifti['y'])
+					else:
+						raise RuntimeError("bamg error message: only a rift tip can be outside of the domain")
+
+					#Get cordinate of intersection point
+					x1=rifti['x'][0]
+					y1=rifti['y'][0]
+					x2=rifti['x'][1]
+					y2=rifti['y'][1]
+					for j in xrange(0,numpy.size(domain[0]['x'])-1):
+						if SegIntersect(numpy.array([[x1,y1],[x2,y2]]),numpy.array([[domain[0]['x'][j],domain[0]['y'][j]],[domain[0]['x'][j+1],domain[0]['y'][j+1]]])):
+
+							#Get position of the two nodes of the edge in domain
+							i1=j
+							i2=j+1
+
+							#rift is crossing edge [i1 i2] of the domain
+							#Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+							x3=domain[0]['x'][i1]
+							y3=domain[0]['y'][i1]
+							x4=domain[0]['x'][i2]
+							y4=domain[0]['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]);
+							x=numpy.linalg.det(numpy.array([[numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),x1-x2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),x3-x4]]))/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
+							y=numpy.linalg.det(numpy.array([[numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4]]))/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
+
+							segdis= sqrt((x4-x3)**2+(y4-y3)**2)
+							tipdis=numpy.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)])
+
+							if numpy.min(tipdis)/segdis < options.getfieldvalue('toltip',0):
+								print "moving tip-domain intersection point"
+
+								#Get position of the closer point
+								if tipdis[0]>tipdis[1]:
+									pos=i2
+								else:
+									pos=i1
+
+								#This point is only in Vertices (number pos).
+								#OK, now we can add our own rift
+								nods=rifti['nods']-1
+								bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((rifti['x'][1:].reshape(-1,1),rifti['y'][1:].reshape(-1,1),numpy.ones((nods,1))))))
+								bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges,\
+									numpy.array([[pos,count+1,(1+i)]]),\
+									numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))
+								count+=nods
+
+								break
+
+							else:
+								#Add intersection point to Vertices
+								bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.array([[x,y,1]])))
+								count+=1
+
+								#Decompose the crossing edge into 2 subedges
+								pos=numpy.nonzero(numpy.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0]
+								if not pos:
+									raise RuntimeError("bamg error message: a problem occurred...")
+								bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges[0:pos-1,:],\
+									numpy.array([[bamg_geometry.Edges[pos,0],count                     ,bamg_geometry.Edges[pos,2]]]),\
+									numpy.array([[count                     ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\
+									bamg_geometry.Edges[pos+1:,:]))
+
+								#OK, now we can add our own rift
+								nods=rifti['nods']-1
+								bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((rifti['x'][1:].reshape(-1,1),rifti['y'][1:].reshape(-1,1),numpy.ones((nods,1))))))
+								bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges,\
+									numpy.array([[count,count+1,2]]),\
+									numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))
+								count+=nods
+
+								break
+
+				else:
+					nods=rifti['nods']-1
+					bamg_geometry.Vertices=numpy.vstack(bamg_geometry.Vertices, numpy.hstack(rifti['x'][:],rifti['y'][:],numpy.ones((nods+1,1))))
+					bamg_geometry.Edges   =numpy.vstack(bamg_geometry.Edges, numpy.hstack(numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),i*numpy.ones((nods,1))))
+					count=+nods+1
+
+		#Deal with tracks
+		if options.exist('tracks'):
+
+			#read tracks
+			track=options.getfieldvalue('tracks')
+			if all(isinstance(track,(str,unicode))):
+				A=expread(track)
+				track=numpy.hstack((A.x.reshape(-1,1),A.y.reshape(-1,1)))
+			else:
+				track=float(track)    #for some reason, it is of class "single"
+			if numpy.size(track,axis=1)==2:
+				track=numpy.hstack((track,3.*numpy.ones((size(track,axis=0),1))))
+
+			#only keep those inside
+			flags=ContourToNodes(track[:,0],track[:,1],domainfile,0)
+			track=track[numpy.nonzero(flags),:]
+
+			#Add all points to bamg_geometry
+			nods=numpy.size(track,axis=0)
+			bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,track))
+			bamg_geometry.Edges   =numpy.vstack((bamg_geometry.Edges,numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),3.*numpy.ones((nods-1,1))))))
+
+			#update counter
+			count+=nods
+
+		#Deal with vertices that need to be kept by mesher
+		if options.exist('RequiredVertices'):
+
+			#recover RequiredVertices
+			requiredvertices=float(options.getfieldvalue('RequiredVertices'))    #for some reason, it is of class "single"
+			if numpy.size(requiredvertices,axis=1)==2:
+				requiredvertices=numpy.hstack((requiredvertices,4.*numpy.ones((numpy.size(requiredvertices,axis=0),1))))
+	
+			#only keep those inside
+			flags=ContourToNodes(requiredvertices[:,0],domain[0],0)
+			requiredvertices=requiredvertices[numpy.nonzero(flags),:]
+
+			#Add all points to bamg_geometry
+			nods=numpy.size(requiredvertices,axis=0)
+			bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,requiredvertices))
+
+			#update counter
+			count+=nods
+
+		#process geom
+		#bamg_geometry=processgeometry(bamg_geometry,options.getfieldvalue('tol',float(nan)),domain[0])
+
+	elif isinstance(md.private.bamg,dict) and 'geometry' in md.private.bamg:
+		bamg_geometry=bamggeom(md.private.bamg['geometry'].__dict__) 
+	else:
+		#do nothing...
+		pass
+	#}}}
+	# Bamg Mesh parameters {{{
+	if not options.exist('domain') and md.mesh.numberofvertices and md.mesh.dimension==2:
+
+		if isinstance(md.private.bamg,dict) and 'mesh' in md.private.bamg:
+			bamg_mesh=bamgmesh(md.private.bamg['mesh'].__dict__)
+		else:
+			bamg_mesh.Vertices=numpy.hstack((md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),numpy.ones((md.mesh.numberofvertices,1))))
+			bamg_mesh.Triangles=numpy.hstack((md.mesh.elements,numpy.ones((md.mesh.numberofelements,1))))
+
+		if isinstance(md.rifts.riftstruct,dict):
+			raise TypeError("bamg error message: rifts not supported yet. Do meshprocessrift AFTER bamg")
+	#}}}
+	# Bamg Options {{{
+	bamg_options['Crack']=options.getfieldvalue('Crack',0)
+	bamg_options['anisomax']=options.getfieldvalue('anisomax',10.**30)
+	bamg_options['coeff']=options.getfieldvalue('coeff',1.)
+	bamg_options['cutoff']=options.getfieldvalue('cutoff',10.**-5)
+	bamg_options['err']=options.getfieldvalue('err',numpy.array([[0.01]]))
+	bamg_options['errg']=options.getfieldvalue('errg',0.1)
+	bamg_options['field']=options.getfieldvalue('field',numpy.empty((0,1)))
+	bamg_options['gradation']=options.getfieldvalue('gradation',1.5)
+	bamg_options['Hessiantype']=options.getfieldvalue('Hessiantype',0)
+	bamg_options['hmin']=options.getfieldvalue('hmin',10.**-100)
+	bamg_options['hmax']=options.getfieldvalue('hmax',10.**100)
+	bamg_options['hminVertices']=options.getfieldvalue('hminVertices',numpy.empty((0,1)))
+	bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',numpy.empty((0,1)))
+	bamg_options['hVertices']=options.getfieldvalue('hVertices',numpy.empty((0,1)))
+	bamg_options['KeepVertices']=options.getfieldvalue('KeepVertices',1)
+	bamg_options['MaxCornerAngle']=options.getfieldvalue('MaxCornerAngle',10.)
+	bamg_options['maxnbv']=options.getfieldvalue('maxnbv',10**6)
+	bamg_options['maxsubdiv']=options.getfieldvalue('maxsubdiv',10.)
+	bamg_options['metric']=options.getfieldvalue('metric',numpy.empty((0,1)))
+	bamg_options['Metrictype']=options.getfieldvalue('Metrictype',0)
+	bamg_options['nbjacobi']=options.getfieldvalue('nbjacobi',1)
+	bamg_options['nbsmooth']=options.getfieldvalue('nbsmooth',3)
+	bamg_options['omega']=options.getfieldvalue('omega',1.8)
+	bamg_options['power']=options.getfieldvalue('power',1.)
+	bamg_options['splitcorners']=options.getfieldvalue('splitcorners',1)
+	bamg_options['geometricalmetric']=options.getfieldvalue('geometricalmetric',0)
+	bamg_options['verbose']=options.getfieldvalue('verbose',1)
+	#}}}
+
+	#call Bamg
+	[bamgmesh_out,bamggeom_out]=BamgMesher(bamg_mesh.__dict__,bamg_geometry.__dict__,bamg_options)
+
+	# 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:2].astype(int)-1]=1
+	md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity
+	md.mesh.elementconnectivity[numpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0
+
+	#Check for orphan
+	if numpy.any(numpy.logical_not(numpy.in1d(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
+		raise RuntimeError("Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)")
+
+	return md
+
+def processgeometry(geom,tol,outline):    # {{{
+
+	raise RuntimeError("bamg.py/processgeometry is not complete.")
+	#Deal with edges
+	print "Checking Edge crossing..."
+	i=0
+	while (i<numpy.size(geom.Edges,axis=0)):
+
+		#edge counter
+		i+=1
+
+		#Get coordinates
+		x1=geom.Vertices[geom.Edges[i,0],0]
+		y1=geom.Vertices[geom.Edges[i,0],1]
+		x2=geom.Vertices[geom.Edges[i,1],0]
+		y2=geom.Vertices[geom.Edges[i,1],1]
+		color1=geom.Edges[i,2]
+
+		j=i    #test edges located AFTER i only
+		while (j<numpy.size(geom.Edges,axis=0)):
+
+			#edge counter
+			j+=1
+
+			#Skip if the two edges already have a vertex in common
+			if any(ismember(geom.Edges[i,0:2],geom.Edges[j,0:2])):
+				continue
+
+			#Get coordinates
+			x3=geom.Vertices[geom.Edges[j,0],0]
+			y3=geom.Vertices[geom.Edges[j,0],1]
+			x4=geom.Vertices[geom.Edges[j,1],0]
+			y4=geom.Vertices[geom.Edges[j,1],1]
+			color2=geom.Edges[j,2]
+
+			#Check if the two edges are crossing one another
+			if SegIntersect(numpy.array([[x1,y1],[x2,y2]]),numpy.array([[x3,y3],[x4,y4]])):
+
+				#Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
+				x=numpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),x1-x2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),x3-x4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
+				y=numpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
+
+				#Add vertex to the list of vertices
+				geom.Vertices=numpy.vstack((geom.Vertices,[x,y,min(color1,color2)]))
+				id=numpy.size(geom.Vertices,axis=0)
+
+				#Update edges i and j
+				edgei=geom.Edges[i,:].copy()
+				edgej=geom.Edges[j,:].copy()
+				geom.Edges[i,:]    =[edgei(0),id      ,edgei(2)]
+				geom.Edges=numpy.vstack((geom.Edges,[id      ,edgei(1),edgei(2)]))
+				geom.Edges[j,:]    =[edgej(0),id      ,edgej(2)]
+				geom.Edges=numpy.vstack((geom.Edges,[id      ,edgej(1),edgej(2)]))
+
+				#update current edge second tip
+				x2=x
+				y2=y
+
+	#Check point outside
+	print "Checking for points outside the domain..."
+	i=0
+	num=0
+	while (i<numpy.size(geom.Vertices,axis=0)):
+
+		#vertex counter
+		i+=1
+
+		#Get coordinates
+		x=geom.Vertices[i,0]
+		y=geom.Vertices[i,1]
+		color=geom.Vertices[i,2]
+
+		#Check that the point is inside the domain
+		if color!=1 and not ContourToNodes(x,y,outline[0],1):
+
+			#Remove points from list of Vertices
+			num+=1
+			geom.Vertices[i,:]=[]
+
+			#update edges
+			posedges=numpy.nonzero(geom.Edges==i)
+			geom.Edges[posedges[0],:]=[]
+			posedges=numpy.nonzero(geom.Edges>i)
+			geom.Edges[posedges]=geom.Edges[posedges]-1
+
+			#update counter
+			i-=1
+
+	if num:
+		print "WARNING: %d points outside the domain outline have been removed" % num
+
+	"""
+	%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)),:)=[];
+	"""
+	return geom
+# }}}
+
Index: /issm/trunk/src/m/mesh/meshconvert.py
===================================================================
--- /issm/trunk/src/m/mesh/meshconvert.py	(revision 13974)
+++ /issm/trunk/src/m/mesh/meshconvert.py	(revision 13975)
@@ -52,5 +52,5 @@
 	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
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].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 13974)
+++ /issm/trunk/src/m/mesh/planet/mesh_refine_tri4.m	(revision 13975)
@@ -29,5 +29,4 @@
 % 
 
-
 % ---this method is not implemented, but the idea here remains...
 % This can be done until some minimal distance (D) of the mean 
@@ -36,5 +35,4 @@
 % 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 $
@@ -80,25 +78,25 @@
 
 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
@@ -106,5 +104,5 @@
     [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 ];
@@ -112,5 +110,5 @@
     F2(f*4-1,:) = [ Nc, Nb, NC ];
     F2(f*4-0,:) = [ Na, Nb, Nc ];
-    
+
 end
 
@@ -121,5 +119,4 @@
 
 return
-
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Index: /issm/trunk/src/m/mesh/planet/planetmixedmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/planetmixedmesh.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/planet/planetmixedmesh.m	(revision 13975)
@@ -33,10 +33,10 @@
 	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
@@ -64,5 +64,4 @@
 quads=[trias;quads];
 
-
 % now add south pole: 
 phii=180*conv;
@@ -85,5 +84,4 @@
 quads=[quads;trias];
 
-
 md.mesh.elements=quads;
 md.mesh.x=x;
Index: /issm/trunk/src/m/mesh/planet/sphere_project.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/sphere_project.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/planet/sphere_project.m	(revision 13975)
@@ -50,5 +50,4 @@
 % use of arctan functions, which have branches.
 
-
 % Convert Cartesian X,Y,Z to spherical (radians)
 theta = atan2( (Y-yo), (X-xo) );
Index: /issm/trunk/src/m/mesh/planet/sphere_tri.m
===================================================================
--- /issm/trunk/src/m/mesh/planet/sphere_tri.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/planet/sphere_tri.m	(revision 13975)
@@ -43,6 +43,4 @@
 % See also: mesh_refine, sphere_project
 %
-
-
 
 % $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
@@ -80,5 +78,4 @@
 end
 
-
 % -----------------
 % define the starting shapes
@@ -88,13 +85,13 @@
 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;
@@ -102,10 +99,10 @@
                 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
@@ -115,5 +112,5 @@
                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
@@ -125,14 +122,14 @@
               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
@@ -147,5 +144,5 @@
     ico.v(11,:) = [   0 , -tau, -one ]; % XC
     ico.v(12,:) = [   0 ,  tau, -one ]; % XD
-    
+
     % Structure for unit icosahedron
     ico.f = [  5,  8,  9 ;
@@ -169,25 +166,24 @@
                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
Index: /issm/trunk/src/m/mesh/rifts/meshaddrifts.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshaddrifts.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/rifts/meshaddrifts.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=meshaddrifts(md,riftname);
+function md=meshaddrifts(md,riftname)
 %MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
 %
@@ -12,5 +12,4 @@
 %        be preserved. There can be as many pairs of closed contour and rift contour as wished.
 
-
 %read rift: 
 domains=expread(riftname,1);
@@ -20,18 +19,18 @@
 %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');
@@ -41,5 +40,5 @@
 		domain_index(end+1)=md2.mesh.segments(pos,2);
 	end
-	
+
 	domain.x=md2.mesh.x(domain_index);
 	domain.y=md2.mesh.y(domain_index);
@@ -47,12 +46,12 @@
 	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,...
@@ -61,9 +60,9 @@
 	%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;
@@ -73,5 +72,5 @@
 		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));
Index: /issm/trunk/src/m/mesh/rifts/meshplug.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshplug.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/rifts/meshplug.m	(revision 13975)
@@ -1,6 +1,5 @@
-function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain);
+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
@@ -48,8 +47,6 @@
 end
 
-
 %plug elements
 elements=[elements;elements2];
-
 
 %now, increase number of nodes
@@ -87,3 +84,2 @@
 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 13974)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.m	(revision 13975)
@@ -6,9 +6,7 @@
 %
 
+%go through rifts, and figure out which ones touch the domain outline
+for i=1:length(md.rifts.riftstruct),
 
-
-%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);
@@ -20,5 +18,5 @@
 	%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, 
@@ -41,5 +39,5 @@
 		elements=[];
 
-		while  flags(B), %as long as B does not belong to the domain outline, keep looking.
+		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);
@@ -52,5 +50,5 @@
 			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.
@@ -59,5 +57,5 @@
 		md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
 		md.mesh.numberofvertices=num;
-		
+
 		%replace tip in elements
 		newelements=md.mesh.elements(elements,:);
@@ -69,5 +67,5 @@
 		%deal with segments
 		tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
-		for  k=1:length(tipsegments),
+		for k=1:length(tipsegments),
 			segment_index=tipsegments(k);
 			pos=find(md.mesh.segments(segment_index,1:2)~=tip);
@@ -81,5 +79,4 @@
 end
 
-
 %Fill in rest of fields:
 md.mesh.numberofelements=length(md.mesh.elements);
@@ -87,5 +84,4 @@
 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);
Index: /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.py
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.py	(revision 13975)
@@ -0,0 +1,110 @@
+import numpy
+from ElementsFromEdge import *
+from MatlabFuncs import *
+
+def 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 rift in md.rifts.riftstruct:
+	
+		#first, flag nodes that belong to the domain outline
+		flags=ContourToMesh(md.mesh.elements,md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),domainoutline,'node',0)
+
+		tips=rift.tips
+		outsidetips=tips[numpy.nonzero(flags[rift.tips-1])[0]]
+
+		#we have found outsidetips, tips that touch the domain outline. go through them
+		for tip in outsidetips:
+		
+			#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=numpy.nonzero(rift.segments[:,0]==tip)[0]
+			if tipindex:
+				tipindex=tipindex[0]
+				node_connected_to_tip=rift.segments[tipindex,1]
+			else:
+				tipindex=numpy.nonzero(rift.segments[:,1]==tip)[0]
+				tipindex=tipindex[0]
+				node_connected_to_tip=rift.segments[tipindex,1]
+
+			#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=numpy.empty(0)
+
+			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(numpy.nonzero(numpy.logical_not(already_detected))[0])
+				#add new detected element to the list of elements we are looking for.
+				elements=numpy.concatenate((elements,nextelement))
+				#new B:
+				B=md.mesh.elements[nextelement-1,numpy.nonzero(numpy.logical_not(ismember(md.mesh.elements[nextelement-1,:],numpy.array([A,B]))))]
+		
+			#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=numpy.size(md.mesh.x)+1
+			md.mesh.x=numpy.concatenate((md.mesh.x,md.mesh.x[tip]))
+			md.mesh.y=numpy.concatenate((md.mesh.y,md.mesh.y[tip]))
+			md.mesh.numberofvertices=num
+		
+			#replace tip in elements
+			newelements=md.mesh.elements[elements.astype(int)-1,:]
+			pos=numpy.nonzero(newelements==tip)
+			newelements[pos]=num
+			md.mesh.elements[elements.astype(int)-1,:]=newelements
+			rift.tips=numpy.concatenate((rift.tips,num))
+
+			#deal with segments
+			tipsegments=numpy.nonzero(numpy.logical_or(md.mesh.segments[:,0]==tip,md.mesh.segments[:,1]==tip))[0]
+			for segment_index in tipsegments:
+				pos=numpy.nonzero(md.mesh.segments[segment_index,0:2]!=tip)[0]
+				other_node=md.mesh.segments[segment_index,pos]
+				if not isconnected(md.mesh.elements,other_node,tip):
+					pos=numpy.nonzero(md.mesh.segments[segment_index,0:2]==tip)[0]
+					md.mesh.segments[segment_index,pos]=num
+
+	#Fill in rest of fields:
+	md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
+	md.mesh.numberofvertices=numpy.size(md.mesh.x)
+	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x))
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1]=1
+	md.rifts.numrifts=length(md.rifts.riftstruct)
+	md.flowequation.element_equation=3.*numpy.ones(md.mesh.numberofelements)
+	md.mesh.vertexonbed=numpy.ones(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)
+
+	return md
+
+def isconnected(elements,A,B):    # {{{
+	"""
+	ISCONNECTED: are two nodes connected by a triangulation?
+
+	   Usage: flag=isconnected(elements,A,B)
+
+	"""
+
+	elements=ElementsFromEdge(elements,A,B)
+	if not elements:
+		flag=0
+	else:
+		flag=1
+
+	return flag
+	# }}}
+
Index: /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py
===================================================================
--- /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/rifts/meshprocessrifts.py	(revision 13975)
@@ -0,0 +1,66 @@
+import numpy
+from TriMeshProcessRifts import *
+from ContourToMesh import *
+from meshprocessoutsiderifts import *
+from GetAreas import *
+
+def 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');
+	
+	"""
+
+	#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)
+	md.mesh.x=md.mesh.x.reshape(-1)
+	md.mesh.y=md.mesh.y.reshape(-1)
+	if not isinstance(md.rifts.riftstruct,list) or not md.rifts.riftstruct:
+		raise RuntimeError("TriMeshProcessRifts did not find any rift")
+
+	#Fill in rest of fields:
+	numrifts=len(md.rifts.riftstruct)
+	md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
+	md.mesh.numberofvertices=numpy.size(md.mesh.x)
+	md.mesh.z=numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x))
+	md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1]=1
+	md.mesh.vertexonbed=numpy.ones(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)
+
+	#get coordinates of rift tips
+	for rift in md.rifts.riftstruct:
+		rift['tip1coordinates']=numpy.hstack((md.mesh.x[rift['tips'][0,0].astype(int)-1].reshape(-1,1),md.mesh.y[rift['tips'][0,0].astype(int)-1].reshape(-1,1)))
+		rift['tip2coordinates']=numpy.hstack((md.mesh.x[rift['tips'][0,1].astype(int)-1].reshape(-1,1),md.mesh.y[rift['tips'][0,1].astype(int)-1].reshape(-1,1)))
+
+	#In case we have rifts that open up the domain outline, we need to open them: 
+	[flags,dum]=ContourToMesh(md.mesh.elements,md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),domainoutline,'node',0)
+	found=0
+	for rift in md.rifts.riftstruct:
+		if flags[rift['tips'][0,0].astype(int)-1]==0:
+			found=1
+			break
+		if flags[rift['tips'][0,1].astype(int)-1]==0:
+			found=1
+			break
+	if found:
+		md=meshprocessoutsiderifts(md,domainoutline)
+
+	#get elements that are not correctly oriented in the correct direction:
+	aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y)
+	pos=numpy.nonzero(aires<0)[0]
+	md.mesh.elements[pos,:]=numpy.hstack((md.mesh.elements[pos,1].reshape(-1,1),md.mesh.elements[pos,0].reshape(-1,1),md.mesh.elements[pos,2].reshape(-1,1)))
+
+	return md
+
Index: /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m	(revision 13975)
@@ -4,5 +4,5 @@
 
 %read rifts from outline file
-rifts=expread(riftoutline,1);
+rifts=expread(riftoutline);
 
 tips=[];
@@ -13,5 +13,5 @@
 	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;
@@ -19,8 +19,7 @@
 	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 13974)
+++ /issm/trunk/src/m/mesh/rifts/rifttipsrefine.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=rifttipsrefine(md,filename,resolution,circleradius);
+function md=rifttipsrefine(md,filename,resolution,circleradius)
 %RIFTTIPSREFINE - refine mesh near rift tips
 %
Index: /issm/trunk/src/m/mesh/roundmesh.m
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.m	(revision 13974)
+++ /issm/trunk/src/m/mesh/roundmesh.m	(revision 13975)
@@ -12,12 +12,12 @@
 
 %Get number of points on the circle
-pointsonedge=floor((2*pi*radius) / resolution);
+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);
+theta=(0.:2.*pi/pointsonedge:2.*pi*(1.-1./pointsonedge))';
+x_list=roundsigfig(radius*x_list.*cos(theta),12);
+y_list=roundsigfig(radius*y_list.*sin(theta),12);
+A=struct('x',x_list,'y',y_list,'density',1.);
 expwrite(A,'RoundDomainOutline.exp');
 
@@ -28,7 +28,21 @@
 %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;
+md.mesh.x(pos)=0.;
+md.mesh.y(pos)=0.;
 
 %delete domain
 delete('RoundDomainOutline.exp')
+end
+
+function x=roundsigfig(x,n)
+
+digits=ceil(log10(abs(x)));
+x=x./10.^digits;
+x=round(x.*10.^n)./10.^n;
+x=x.*10.^digits;
+
+pos=find(isnan(x));
+x(pos)=0.;
+
+end
+
Index: /issm/trunk/src/m/mesh/roundmesh.py
===================================================================
--- /issm/trunk/src/m/mesh/roundmesh.py	(revision 13975)
+++ /issm/trunk/src/m/mesh/roundmesh.py	(revision 13975)
@@ -0,0 +1,62 @@
+import numpy
+import os
+from collections import OrderedDict
+from expwrite import *
+from triangle import *
+#from bamg import *
+
+def 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=numpy.floor((2.*numpy.pi*radius) / resolution)
+
+	#Calculate the cartesians coordinates of the points
+	x_list=numpy.ones(pointsonedge)
+	y_list=numpy.ones(pointsonedge)
+	theta=numpy.linspace(0.,2.*numpy.pi,num=pointsonedge,endpoint=False)
+	x_list=roundsigfig(radius*x_list*numpy.cos(theta),12)
+	y_list=roundsigfig(radius*y_list*numpy.sin(theta),12)
+	A=OrderedDict()
+	A['x']=x_list
+	A['y']=y_list
+	A['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
+	pos=numpy.argmin(md.mesh.x**2+md.mesh.y**2)
+	md.mesh.x[pos]=0.
+	md.mesh.y[pos]=0.
+
+	#delete domain
+	os.remove('RoundDomainOutline.exp')
+
+	return md
+
+def roundsigfig(x,n):
+
+	digits=numpy.ceil(numpy.log10(numpy.abs(x)))
+	x=x/10.**digits
+	x=numpy.round(x,decimals=n)
+	x=x*10.**digits
+
+	pos=numpy.nonzero(numpy.isnan(x))
+	x[pos]=0.
+
+	return x
+
Index: /issm/trunk/src/m/mesh/triangle.py
===================================================================
--- /issm/trunk/src/m/mesh/triangle.py	(revision 13974)
+++ /issm/trunk/src/m/mesh/triangle.py	(revision 13975)
@@ -1,56 +1,66 @@
-from numpy import *
-import TriMesh as tm
-import NodeConnectivity as nc
-import ElementConnectivity as ec
+import numpy
+from TriMesh import *
+from NodeConnectivity import *
+from ElementConnectivity import *
+from MatlabFuncs import *
 
-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');
+def triangle(md,domainname,*args):
+	"""
+	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). 
 
+	if len(args)==1:
+		resolution=args[0]
+		riftname=''
+	if len(args)==2:
+		riftname=args[0]
+		resolution=args[1]
+
 	#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':
+	if md.mesh.numberofelements:
+		choice = raw_input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
+		if not strcmp(choice,'y'):
 			print 'no meshing done ... exiting'
-			return []
-		
-	area = resolution**2.
+			return None
+
+	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)
-
+	[md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=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.numberofelements = numpy.size(md.mesh.elements,axis=0)
+	md.mesh.numberofvertices = numpy.size(md.mesh.x)
+	md.mesh.z = numpy.zeros(md.mesh.numberofvertices)
+	md.mesh.vertexonboundary = numpy.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)
+	md.mesh.vertexonbed = numpy.ones(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)
 
 	#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)
-	
+	[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.
+
 	return md
+
Index: sm/trunk/src/m/miscellaneous/BinRead.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/BinRead.py	(revision 13974)
+++ 	(revision )
@@ -1,168 +1,0 @@
-#! /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 13974)
+++ /issm/trunk/src/m/miscellaneous/MatlabFuncs.py	(revision 13975)
@@ -53,8 +53,38 @@
 
 	else:
-		b=numpy.empty_like(a)
-		for i,item in enumerate(a.flat):
-			b.flat[i]=item in s
+		if not isinstance(s,numpy.ndarray):
+			b=numpy.empty_like(a)
+			for i,item in enumerate(a.flat):
+				b.flat[i]=item in s
+		else:
+			b=numpy.in1d(a.flat,s.flat).reshape(a.shape)
 
 	return b
 
+def det(a):
+	import numpy
+
+	if   a.shape==(1,):
+		return a[0]
+	elif a.shape==(1,1):
+		return a[0,0]
+	elif a.shape==(2,2):
+		return a[0,0]*a[1,1]-a[0,1]*a[1,0]
+	else:
+		raise TypeError("MatlabFunc.det only implemented for shape (2, 2), not for shape %s." % str(a.shape))
+
+def sparse(ivec,jvec,svec,m=0,n=0,nzmax=0):
+	import numpy
+
+	if not m:
+		m=numpy.max(ivec)
+	if not n:
+		n=numpy.max(jvec)
+
+	a=numpy.zeros((m,n))
+
+	for i,j,s in zip(ivec.reshape(-1,order='F'),jvec.reshape(-1,order='F'),svec.reshape(-1,order='F')):
+		a[i-1,j-1]+=s
+
+	return a
+
Index: /issm/trunk/src/m/miscellaneous/fielddisplay.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 13974)
+++ /issm/trunk/src/m/miscellaneous/fielddisplay.m	(revision 13975)
@@ -13,5 +13,5 @@
 end %function
 
-function parsedisplay(offset,name,field,comment); %{{{
+function parsedisplay(offset,name,field,comment) %{{{
 
 	%string
Index: /issm/trunk/src/m/miscellaneous/fielddisplay.py
===================================================================
--- /issm/trunk/src/m/miscellaneous/fielddisplay.py	(revision 13974)
+++ /issm/trunk/src/m/miscellaneous/fielddisplay.py	(revision 13975)
@@ -50,4 +50,8 @@
 	elif isinstance(field,(list,tuple)):
 		string=list_display(offset,name,field,comment)
+
+	#None
+	elif field is None:
+		string=displayunit(offset,name,"None",comment)
 
 	else:
@@ -128,5 +132,5 @@
 			string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment[0])
 			for commenti in comment:
-				string+="\n%s%-23s  %-15s    %s" % (offset,'','',comment[i])
+				string+="\n%s%-23s  %-15s    %s" % (offset,'','',commenti)
 		else:
 			raise RuntimeError("fielddisplay error message: format for comment not supported yet")
Index: /issm/trunk/src/m/miscellaneous/isnans.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/isnans.m	(revision 13974)
+++ /issm/trunk/src/m/miscellaneous/isnans.m	(revision 13975)
@@ -5,5 +5,4 @@
 %
 %  See also : ISNAN 
-
 
 if isstruct(array), 
Index: /issm/trunk/src/m/miscellaneous/issmdoc.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 13974)
+++ /issm/trunk/src/m/miscellaneous/issmdoc.m	(revision 13975)
@@ -4,12 +4,12 @@
 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)'));
+disp('  A comprehensive documentation is available on http://issm.jpl.nasa.gov');
+disp('  Example: how to create a square ice shelf');
+disp(['       go to ',ISSM_DIR,'/examples/SquareIceShelf']);
+disp(sprintf('%-63s %s','       md=model;','%creates a new empty model structure'));
+disp(sprintf('%-63s %s','       md=triangle(md,''DomainOutline.exp'',50000);','%creates a mesh of the domain outline with a resolution of 50000 m'));
+disp(sprintf('%-63s %s','       md=setmask(md,''all'','''');','%defines the glacier system as an ice shelf (no island)'));
+disp(sprintf('%-63s %s','       md=parameterize(md,''Square.par'');','%fills all the other fields of the model'));
+disp(sprintf('%-63s %s','       md=setflowequation(md,''macayeal'',''all'');','%defines all elements as MacAyeal''s SSA'));
+disp(sprintf('%-63s %s','       md=solve(md,DiagnosticSolutionEnum());','%solve for stress balance'));
+disp(sprintf('%-63s %s','       plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);','%displays the velocity (type plotdoc for plotmodel help)'));
Index: /issm/trunk/src/m/miscellaneous/parallelrange.m
===================================================================
--- /issm/trunk/src/m/miscellaneous/parallelrange.m	(revision 13974)
+++ /issm/trunk/src/m/miscellaneous/parallelrange.m	(revision 13975)
@@ -12,5 +12,4 @@
 end
 
-
 %There may be some rows left. Distribute evenly.
 row_rest=globalsize - numprocs*floor(globalsize/numprocs);
Index: /issm/trunk/src/m/os/ismpi.m
===================================================================
--- /issm/trunk/src/m/os/ismpi.m	(revision 13974)
+++ /issm/trunk/src/m/os/ismpi.m	(revision 13975)
@@ -4,5 +4,4 @@
 %   Usage:
 %       flag=ismpi();
-
 
 configfile=[issmdir() '/bin/config.h']; %should find it in the install target
Index: /issm/trunk/src/m/os/ismumps.m
===================================================================
--- /issm/trunk/src/m/os/ismumps.m	(revision 13974)
+++ /issm/trunk/src/m/os/ismumps.m	(revision 13975)
@@ -4,5 +4,4 @@
 %   Usage:
 %       flag=ismumps();
-
 
 configfile=[issmdir() '/bin/config.h']; %should find it in the install target
Index: /issm/trunk/src/m/os/ispetsc.m
===================================================================
--- /issm/trunk/src/m/os/ispetsc.m	(revision 13974)
+++ /issm/trunk/src/m/os/ispetsc.m	(revision 13975)
@@ -4,5 +4,4 @@
 %   Usage:
 %       flag=ispetsc();
-
 
 configfile=[issmdir() '/bin/config.h']; %should find it in the install target
Index: /issm/trunk/src/m/os/issmbbftpin.m
===================================================================
--- /issm/trunk/src/m/os/issmbbftpin.m	(revision 13974)
+++ /issm/trunk/src/m/os/issmbbftpin.m	(revision 13975)
@@ -35,5 +35,5 @@
 	end
 	command=[command '''  pfe1.nas.nasa.gov'];
-	
+
 	eval(command);
 
@@ -45,4 +45,3 @@
 	end
 
-
 end
Index: /issm/trunk/src/m/os/issmbbftpout.m
===================================================================
--- /issm/trunk/src/m/os/issmbbftpout.m	(revision 13974)
+++ /issm/trunk/src/m/os/issmbbftpout.m	(revision 13975)
@@ -19,5 +19,5 @@
 	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 '; ']
@@ -26,5 +26,5 @@
 	end
 	command=[command '''  pfe1.nas.nasa.gov'];
-	
+
 	eval(command);
 end
Index: /issm/trunk/src/m/os/issmscpin.m
===================================================================
--- /issm/trunk/src/m/os/issmscpin.m	(revision 13974)
+++ /issm/trunk/src/m/os/issmscpin.m	(revision 13975)
@@ -31,5 +31,5 @@
 	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%]');
@@ -62,5 +62,4 @@
 		end
 
-
 		if port,
 			eval(['!scp -P ' num2str(port) ' ' login '@localhost:' path '/' string ' ./']);
@@ -68,5 +67,5 @@
 			eval(['!scp ' login '@' host ':' path '/' string ' ./']);
 		end
-		
+
 		%check scp worked
 		for i=1:numel(packages),
Index: /issm/trunk/src/m/os/issmscpout.m
===================================================================
--- /issm/trunk/src/m/os/issmscpout.m	(revision 13974)
+++ /issm/trunk/src/m/os/issmscpout.m	(revision 13975)
@@ -22,5 +22,5 @@
 	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%]');
@@ -48,5 +48,5 @@
 		end
 		string=[string ' '];
-		
+
 		if port,
 			eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
Index: /issm/trunk/src/m/os/issmssh.m
===================================================================
--- /issm/trunk/src/m/os/issmssh.m	(revision 13974)
+++ /issm/trunk/src/m/os/issmssh.m	(revision 13975)
@@ -14,5 +14,5 @@
 	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%]');
Index: /issm/trunk/src/m/os/issmssh.py
===================================================================
--- /issm/trunk/src/m/os/issmssh.py	(revision 13974)
+++ /issm/trunk/src/m/os/issmssh.py	(revision 13975)
@@ -40,2 +40,20 @@
 				subprocess.call('ssh -l %s %s "%s"' % (login,host,command),shell=True)
 
+	# The following code was added to fix:
+	# "IOError: [Errno 35] Resource temporarily unavailable"
+	# on the Mac when trying to display md after the solution.
+	# (from http://code.google.com/p/robotframework/issues/detail?id=995)
+
+	# Make FreeBSD use blocking I/O like other platforms
+	import sys
+	import fcntl
+	from os import O_NONBLOCK
+
+	fd = sys.stdin.fileno()
+	flags = fcntl.fcntl(fd, fcntl.F_GETFL)
+	fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
+
+	fd = sys.stdout.fileno()
+	flags = fcntl.fcntl(fd, fcntl.F_GETFL)
+	fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
+
Index: /issm/trunk/src/m/os/issmstscpin.m
===================================================================
--- /issm/trunk/src/m/os/issmstscpin.m	(revision 13975)
+++ /issm/trunk/src/m/os/issmstscpin.m	(revision 13975)
@@ -0,0 +1,37 @@
+function issmstscpin(host, login,path, packages)
+%ISSMSCPIN get packages from host, using scp on unix, and pscp on windows
+%
+%   usage: issmstscpin(host,long, path, packages)
+%
+%
+
+%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);
+
+%use starcluster to 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 ' ' path packages{i} ' '];
+	end
+	string=[string path packages{end}];
+end
+
+system([starcluster() ' get ' host ' -u ' login ' ' string  ' ./']);
+
+%check starcluster get  worked
+for i=1:numel(packages),
+	if ~exist(['./' packages{i}]),
+		error('issmstscpin error message: could not call scp on *nix system');
+	end
+end
Index: /issm/trunk/src/m/os/issmstscpout.m
===================================================================
--- /issm/trunk/src/m/os/issmstscpout.m	(revision 13975)
+++ /issm/trunk/src/m/os/issmstscpout.m	(revision 13975)
@@ -0,0 +1,15 @@
+function issmstscpout(host,path,login,packages)
+%ISSMSTSCPOUT send packages to a host, using starcluster put on unix
+%
+%   usage: issmstscpout(host,path,login,packages)
+%
+%
+
+%create string of packages being sent
+string='';
+for i=1:numel(packages),
+	string=[string ' ' packages{i}];
+end
+string=[string ' '];
+
+system([ starcluster() ' put ' host ' -u ' login ' ' string ' ' path]);
Index: /issm/trunk/src/m/os/issmstssh.m
===================================================================
--- /issm/trunk/src/m/os/issmstssh.m	(revision 13975)
+++ /issm/trunk/src/m/os/issmstssh.m	(revision 13975)
@@ -0,0 +1,8 @@
+function issmstssh(host,login,command)
+%ISSMSSH - wrapper for OS independent ssh command.
+%
+%   usage: 
+%      issmstssh(host,command)
+
+%just use starcluster command to pipe an ssh command through
+system([starcluster() ' sshmaster ' host ' --user ' login ' ''' command '''']);
Index: /issm/trunk/src/m/os/oshostname.m
===================================================================
--- /issm/trunk/src/m/os/oshostname.m	(revision 13974)
+++ /issm/trunk/src/m/os/oshostname.m	(revision 13975)
@@ -7,10 +7,8 @@
 
 if ispc(),
-	[status,hostname]=system('hostname | sed ''s/-//g''');hostname=hostname(1:end-1);
-
+	[status,hostname]=system('hostname | sed ''s/-//g''');
 	if status, 
 		error('oshostname error message: could not run hostname command on windows os');
 	end
-
 else
 	[status,hostname]=system(['hostname -s | sed ''s/-//g''']);
@@ -18,5 +16,8 @@
 		error('oshostname error message: could not run hostname command on *nix os');
 	end
-	hostname=hostname(1:end-1);
-	hostname=ddewhite(hostname);
+
 end
+
+%remove carriage return and blank spaces
+hostname=hostname(1:end-1);
+hostname=ddewhite(hostname);
Index: /issm/trunk/src/m/os/starcluster.m
===================================================================
--- /issm/trunk/src/m/os/starcluster.m	(revision 13975)
+++ /issm/trunk/src/m/os/starcluster.m	(revision 13975)
@@ -0,0 +1,7 @@
+function STARCLUSTER=starcluster()
+%STARCLUSTER - Get path to STARCLUSTER command
+%
+%   Usage:
+%      STARCLUSTER=STARCLUSTER()
+
+STARCLUSTER=[issmdir() '/externalpackages/python/install/bin/starcluster -c ' jplsvn '/projects/CloudComputing/starcluster.config'];
Index: /issm/trunk/src/m/parameterization/contourenvelope.m
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 13974)
+++ /issm/trunk/src/m/parameterization/contourenvelope.m	(revision 13975)
@@ -20,5 +20,4 @@
 	if ischar(flags),
 		file=flags;
-		file=varargin{1};
 		if ~exist(file),
 			error(['contourenvelope error message: file ' file ' not found']);
@@ -29,5 +28,5 @@
 		isfile=0;
 	else
-		error('contourenvelope error message:  second argument should a file or an elements flag');
+		error('contourenvelope error message:  second argument should be a file or an elements flag');
 	end
 end
@@ -70,8 +69,8 @@
 	else
 		%get flag list of elements and nodes inside the contour
-		nodein=zeros(mesh.numberofvertices,1); 
-		elemin=zeros(mesh.numberofelements,1); 
-		
-		pos=find(flags); 
+		nodein=zeros(mesh.numberofvertices,1);
+		elemin=zeros(mesh.numberofelements,1);
+
+		pos=find(flags);
 		elemin(pos)=1;
 		nodein(mesh.elements(pos,:))=1;
@@ -95,5 +94,5 @@
 pos=find(elementonboundary);
 num_segments=length(pos);
-segments=zeros(num_segments,3);
+segments=zeros(num_segments*3,3);
 count=1;
 
@@ -138,2 +137,4 @@
 	end
 end
+segments=segments(1:count-1,:);
+
Index: /issm/trunk/src/m/parameterization/contourenvelope.py
===================================================================
--- /issm/trunk/src/m/parameterization/contourenvelope.py	(revision 13975)
+++ /issm/trunk/src/m/parameterization/contourenvelope.py	(revision 13975)
@@ -0,0 +1,134 @@
+import os.path
+import numpy
+import copy
+from NodeConnectivity import *
+from ElementConnectivity import *
+from mesh import *
+
+def contourenvelope(md,*args):
+	"""
+	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 len(args)>1:
+		raise RuntimeError("contourenvelope error message: bad usage")
+
+	if len(args)==1:
+		flags=args[0]
+
+		if   isinstance(flags,(str,unicode)):
+			file=flags
+			if not os.path.exists(file):
+				raise IOError("contourenvelope error message: file '%s' not found" % file)
+			isfile=1
+		elif isinstance(flags,(bool,int,long,float)):
+			#do nothing for now
+			isfile=0
+		else:
+			raise TypeError("contourenvelope error message:  second argument should be a file or an elements flag")
+
+	#Now, build the connectivity tables for this mesh.
+	#Computing connectivity
+	if numpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and numpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d:
+		[md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)
+	if numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:
+		[md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)
+
+	#get nodes inside profile
+	mesh.elementconnectivity=copy.deepcopy(md.mesh.elementconnectivity)
+	if md.mesh.dimension==2:
+		mesh.elements=copy.deepcopy(md.mesh.elements)
+		mesh.x=copy.deepcopy(md.mesh.x)
+		mesh.y=copy.deepcopy(md.mesh.y)
+		mesh.numberofvertices=copy.deepcopy(md.mesh.numberofvertices)
+		mesh.numberofelements=copy.deepcopy(md.mesh.numberofelements)
+	else:
+		mesh.elements=copy.deepcopy(md.mesh.elements2d)
+		mesh.x=copy.deepcopy(md.mesh.x2d)
+		mesh.y=copy.deepcopy(md.mesh.y2d)
+		mesh.numberofvertices=copy.deepcopy(md.mesh.numberofvertices2d)
+		mesh.numberofelements=copy.deepcopy(md.mesh.numberofelements2d)
+
+	if len(args)==1:
+
+		if isfile:
+			#get flag list of elements and nodes inside the contour
+			nodein=ContourToMesh(mesh.elements,mesh.x,mesh.y,file,'node',1)
+			elemin=(numpy.sum(nodein(mesh.elements),axis=1)==numpy.size(mesh.elements,axis=1))
+			#modify element connectivity
+			elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
+			mesh.elementconnectivity[elemout,:]=0
+			mesh.elementconnectivity[numpy.nonzero(ismember(mesh.elementconnectivity,elemout+1))]=0
+		else:
+			#get flag list of elements and nodes inside the contour
+			nodein=numpy.zeros(mesh.numberofvertices)
+			elemin=numpy.zeros(mesh.numberofelements)
+
+			pos=numpy.nonzero(flags)
+			elemin[pos]=1
+			nodein[mesh.elements[pos,:].astype(int)-1]=1
+
+			#modify element connectivity
+			elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
+			mesh.elementconnectivity[elemout,:]=0
+			mesh.elementconnectivity[numpy.nonzero(ismember(mesh.elementconnectivity,elemout+1))]=0
+
+	#Find element on boundary
+	#First: find elements on the boundary of the domain
+	flag=copy.deepcopy(mesh.elementconnectivity)
+	if len(args)==1:
+		flag[numpy.nonzero(flag)]=elemin[flag[numpy.nonzero(flag)]]
+	elementonboundary=numpy.logical_and(numpy.prod(flag,axis=1)==0,numpy.sum(flag,axis=1)>0).astype(float)
+
+	#Find segments on boundary
+	pos=numpy.nonzero(elementonboundary)[0]
+	num_segments=numpy.size(pos)
+	segments=numpy.zeros((num_segments*3,3))
+	count=0
+
+	for el1 in pos:
+		els2=mesh.elementconnectivity[el1,numpy.nonzero(mesh.elementconnectivity[el1,:])[0]].astype(int)-1
+		if numpy.size(els2)>1:
+			flag=numpy.intersect1d(mesh.elements[els2[0],:],mesh.elements[els2[1],:])
+			nods1=mesh.elements[el1,:]
+			nods1=numpy.delete(nods1,numpy.nonzero(nods1==flag))
+			segments[count,:]=[nods1[0],nods1[1],el1+1]
+
+			ord1=numpy.nonzero(nods1[0]==mesh.elements[el1,:])[0][0]
+			ord2=numpy.nonzero(nods1[1]==mesh.elements[el1,:])[0][0]
+
+			#swap segment nodes if necessary
+			if ( (ord1==0 and ord2==1) or (ord1==1 and ord2==2) or (ord1==2 and ord2==0) ):
+				temp=segments[count,0]
+				segments[count,0]=segments[count,1]
+				segments[count,1]=temp
+			segments[count,0:2]=numpy.flipud(segments[count,0:2])
+			count+=1
+		else:
+			nods1=mesh.elements[el1,:]
+			flag=numpy.setdiff1d(nods1,mesh.elements[els2,:])
+			for j in xrange(0,3):
+				nods=numpy.delete(nods1,j)
+				if numpy.any(ismember(flag,nods)):
+					segments[count,:]=[nods[0],nods[1],el1+1]
+					ord1=numpy.nonzero(nods[0]==mesh.elements[el1,:])[0][0]
+					ord2=numpy.nonzero(nods[1]==mesh.elements[el1,:])[0][0]
+					if ( (ord1==0 and ord2==1) or (ord1==1 and ord2==2) or (ord1==2 and ord2==0) ):
+						temp=segments[count,0]
+						segments[count,0]=segments[count,1]
+						segments[count,1]=temp
+					segments[count,0:2]=numpy.flipud(segments[count,0:2])
+					count+=1
+	segments=segments[0:count,:]
+
+	return segments
+
Index: /issm/trunk/src/m/parameterization/parameterize.m
===================================================================
--- /issm/trunk/src/m/parameterization/parameterize.m	(revision 13974)
+++ /issm/trunk/src/m/parameterization/parameterize.m	(revision 13975)
@@ -56,3 +56,2 @@
 end
 md.miscellaneous.notes=['Model created by using parameter file: ' parametername ' on: ' datestr(now)];
-
Index: /issm/trunk/src/m/parameterization/setflowequation.py
===================================================================
--- /issm/trunk/src/m/parameterization/setflowequation.py	(revision 13974)
+++ /issm/trunk/src/m/parameterization/setflowequation.py	(revision 13975)
@@ -94,8 +94,8 @@
 		                              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
+		                              numpy.logical_and(nodeonpattyn,nodeonstokes).reshape(-1,1)).astype(int)    #find all the nodes on the boundary of the domain without icefront
 #		fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
 		fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements.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
+		stokesflag[numpy.nonzero(fullspcelems.reshape(-1))]=0
 		nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
 
@@ -123,5 +123,5 @@
 		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
+		bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[0:numnodes2d],nodeonmacayeal[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
 
 		#initialize and fill in penalties structure
@@ -129,5 +129,5 @@
 			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)
+				penalties=numpy.vstack((penalties,numpy.hstack((bordernodes2d.reshape(-1,1),bordernodes2d.reshape(-1,1)+md.mesh.numberofvertices2d*(i)))))
 			md.diagnostic.vertex_pairing=penalties
 
@@ -137,5 +137,5 @@
 			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))
+			matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonmacayealpattyn)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
 			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
@@ -146,12 +146,12 @@
 
 			#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)
+			pos=numpy.nonzero(macayealpattynflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
 			macayealflag[pos[pos1]]=1
 			macayealpattynflag[pos[pos1]]=0
-			pos2=numpy.nonzero(elist==-1)
+			pos2=numpy.nonzero(elist==-1)[0]
 			pattynflag[pos[pos2]]=1
 			macayealpattynflag[pos[pos2]]=0
@@ -169,5 +169,5 @@
 			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))
+			matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonpattynstokes)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
 			commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
@@ -178,12 +178,12 @@
 
 			#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)
+			pos=numpy.nonzero(pattynstokesflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
 			stokesflag[pos[pos1]]=1
 			pattynstokesflag[pos[pos1]]=0
-			pos2=numpy.nonzero(elist==-1)
+			pos2=numpy.nonzero(elist==-1)[0]
 			pattynflag[pos[pos2]]=1
 			pattynstokesflag[pos[pos2]]=0
@@ -201,5 +201,5 @@
 			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))
+			matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonmacayealstokes)[0])
 			commonelements=numpy.sum(matrixelements,axis=1)!=0
 			commonelements[numpy.nonzero(macayealflag)]=0    #only one layer: the elements previously in macayeal
@@ -210,12 +210,12 @@
 
 			#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)
+			pos=numpy.nonzero(macayealstokesflag)[0]
+			elist=numpy.zeros(numpy.size(pos),dtype=int)
+			elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
+			elist = elist - numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1).astype(bool)
+			pos1=numpy.nonzero(elist==1)[0]
 			macayealflag[pos[pos1]]=1
 			macayealstokesflag[pos[pos1]]=0
-			pos2=numpy.nonzero(elist==-1)
+			pos2=numpy.nonzero(elist==-1)[0]
 			stokesflag[pos[pos2]]=1
 			macayealstokesflag[pos[pos2]]=0
Index: /issm/trunk/src/m/parameterization/setmask.py
===================================================================
--- /issm/trunk/src/m/parameterization/setmask.py	(revision 13974)
+++ /issm/trunk/src/m/parameterization/setmask.py	(revision 13975)
@@ -1,21 +1,23 @@
-from numpy import *
-import FlagElements as fe
+import numpy
+from FlagElements import *
 
 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');
+	"""
+	SETMASK - establish boundaries between grounded and floating ice.
 
-	#%Get assigned fields
+	   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
@@ -23,33 +25,27 @@
 
 	#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) 
+	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 = logical_and(elementonfloatingice,~elementongroundedice)
-	elementongroundedice = ~elementonfloatingice
+	elementonfloatingice = numpy.logical_and(elementonfloatingice,numpy.logical_not(elementongroundedice))
+	elementongroundedice = numpy.logical_not(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;
-	#%}}}
+	vertexonfloatingice = numpy.zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice = numpy.zeros(md.mesh.numberofvertices,'bool')
+	vertexongroundedice[md.mesh.elements[numpy.nonzero(elementongroundedice),:].astype(int)-1]=True
+	vertexonfloatingice[numpy.nonzero(numpy.logical_not(vertexongroundedice))]=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)
+	md.mask.elementonfloatingice = elementonfloatingice.astype(float)
+	md.mask.vertexonfloatingice = vertexonfloatingice.astype(float)
+	md.mask.elementongroundedice = elementongroundedice.astype(float)
+	md.mask.vertexongroundedice = vertexongroundedice.astype(float)
+	md.mask.vertexonwater = numpy.zeros(md.mesh.numberofvertices)
+	md.mask.elementonwater = numpy.zeros(md.mesh.numberofelements)
+
 	return md
Index: /issm/trunk/src/m/partition/AreaAverageOntoPartition.m
===================================================================
--- /issm/trunk/src/m/partition/AreaAverageOntoPartition.m	(revision 13974)
+++ /issm/trunk/src/m/partition/AreaAverageOntoPartition.m	(revision 13975)
@@ -15,5 +15,5 @@
 	%save 3D model
 	md3d=md;
-	
+
 	md.mesh.elements=md.mesh.elements2d;
 	md.mesh.x=md.mesh.x2d;
Index: /issm/trunk/src/m/partition/adjacency.m
===================================================================
--- /issm/trunk/src/m/partition/adjacency.m	(revision 13974)
+++ /issm/trunk/src/m/partition/adjacency.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=adjacency(md);
+function md=adjacency(md)
 %ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
 %
Index: /issm/trunk/src/m/partition/flagedges.m
===================================================================
--- /issm/trunk/src/m/partition/flagedges.m	(revision 13974)
+++ /issm/trunk/src/m/partition/flagedges.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [xsegments ysegments]=flagedges(elements,x,y,partition);
+function [xsegments ysegments]=flagedges(elements,x,y,partition)
 %FLAGEDGES - return pairs of x,y segments, delimiting partitions.
 %
Index: /issm/trunk/src/m/partition/partitioner.m
===================================================================
--- /issm/trunk/src/m/partition/partitioner.m	(revision 13974)
+++ /issm/trunk/src/m/partition/partitioner.m	(revision 13975)
@@ -50,5 +50,4 @@
 end
 
-
 if strcmpi(package,'chaco'),
 
@@ -57,5 +56,5 @@
 	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)
@@ -68,5 +67,5 @@
 		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.
@@ -79,7 +78,6 @@
 	end
 	maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
-	
+
 	part=maptab(:,2);%index partitions from 1 up. like metis.
-
 
 elseif strcmpi(package,'linear'),
Index: /issm/trunk/src/m/plot/applyoptions.m
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.m	(revision 13974)
+++ /issm/trunk/src/m/plot/applyoptions.m	(revision 13975)
@@ -6,5 +6,4 @@
 %
 %   See also: PLOTMODEL, PARSE_OPTIONS
-		
 
 %some defaults
@@ -147,5 +146,5 @@
 	end
 	if exist(options,'log'),
-		nlab=5;
+		nlab=length(get(c,'YTick'));
 		logvalue=getfieldvalue(options,'log');
 
@@ -176,5 +175,5 @@
 	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'));
+			'Color',getfieldvalue(options,'FontColor','k'));
 	end
 	if exist(options,'colorbarwidth'),
@@ -215,7 +214,7 @@
 			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));
+		labels = cell(1,numel(tick_vals));
+		for i = 1:numel(tick_vals)
+			labels{i} = num2str(tick_vals(i));
 		end
 		set(c,'YTickLabel',labels);
@@ -226,7 +225,6 @@
 else
 	%do nothing
-	
-end
-
+
+end
 
 %area
@@ -269,4 +267,10 @@
 end
 
+%curved arrow
+if exist(options,'curvedarrow'),
+	curvedoptions=getfieldvalue(options,'curvedarrow');
+	curvedarrow(curvedoptions{:});
+end
+
 %Scale ruler
 if exist(options,'scaleruler'),
@@ -320,8 +324,7 @@
 end
 
-
 %position of figure
 if exist(options,'figposition'),
-	
+
 	figposition=getfieldvalue(options,'figposition');
 	if ischar(figposition),
@@ -430,5 +433,5 @@
 	data=getfieldvalue(options,'scatter');
 	hold on
-	plot_scatter(data(:,1),data(:,2),getfieldvalue(options,'scattersize',3),data(:,3),options);
+	plot_scatter(data(:,1),data(:,2),data(:,3),options);
 end
 
Index: /issm/trunk/src/m/plot/applyoptions.py
===================================================================
--- /issm/trunk/src/m/plot/applyoptions.py	(revision 13975)
+++ /issm/trunk/src/m/plot/applyoptions.py	(revision 13975)
@@ -0,0 +1,192 @@
+
+try:
+	import pylab as p
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+def applyoptions(md,data,options):
+	'''
+	APPLYOPTIONS - apply options to current plot
+
+		Usage:
+			applyoptions(md,data,options)
+
+		See also: PLOTMODEL, PARSE_OPTIONS
+	'''
+
+	#some defaults (this seems to be adding a field that already exists...)
+	#if not isnan(md.mesh.hemisphere):
+	#	options.addfielddefault('hemisphere',md.mesh.hemisphere)
+
+	#font {{{
+	fontsize=options.getfieldvalue('fontsize',14)
+	fontweight=options.getfieldvalue('fontweight','normal')
+	fontfamily=options.getfieldvalue('fontfamily','sans-serif')
+	font={
+			'fontsize'		:fontsize,
+			'fontweight'	:fontweight,
+			'family'			:fontfamily
+			}
+	#}}}
+
+	#title {{{
+	if options.exist('title'):
+		title=options.getfieldvalue('title')
+		if options.exist('titlefontsize'):
+			titlefontsize=options.getfieldvalue('titlefontsize')
+		else:
+			titlefontsize=fontsize
+		if options.exist('titlefontweight'):
+			titlefontweight=options.getfieldvalue('titlefontweight')
+		else:
+			titlefontweight=fontweight
+		#title font
+		titlefont=font.copy()
+		titlefont['size']=titlefontsize
+		titlefont['weight']=titlefontweight
+		p.title(title,**titlefont)
+	#}}}
+		
+	#xlabel, ylabel, zlabel {{{
+	if options.exist('labelfontsize'):
+		labelfontsize=options.getfieldvalue('labelfontsize')
+	else:
+		labelfontsize=fontsize
+	if options.exist('labelfontweight'):
+		labelfontweight=options.getfieldvalue('labelfontweight')
+	else:
+		labelfontweight=fontweight
+
+	#font dict for labels
+	labelfont=font.copy()
+	labelfont['fontsize']=labelfontsize
+	labelfont['fontweight']=labelfontweight
+
+	if options.exist('xlabel'):
+		p.xlabel(options.getfieldvalue('xlabel'),**labelfont)
+	if options.exist('ylabel'):
+		p.ylabel(options.getfieldvalue('ylabel'),**labelfont)
+	if options.exist('zlabel'):
+		p.zlabel(options.getfieldvalue('zlabel'),**labelfont)
+	#}}}
+
+	#xticks, yticks, zticks (tick locations) {{{
+	if options.exist('xticks'):
+		if options.exist('xticklabels'):
+			xticklabels=options.getfieldvalue('xticklabels')
+			p.xticks(options.getfieldvalue('xticks'),xticklabels)
+		else:
+			p.xticks(options.getfieldvalue('xticks'))
+	if options.exist('yticks'):
+		if options.exist('yticklabels'):
+			yticklabels=options.getfieldvalue('yticklabels')
+			p.yticks(options.getfieldvalue('yticks'),yticklabels)
+		else:
+			p.yticks(options.getfieldvalue('yticks'))
+	if options.exist('zticks'):
+		if options.exist('zticklabels'):
+			zticklabels=options.getfieldvalue('zticklabels')
+			p.zticks(options.getfieldvalue('zticks'),zticklabels)
+		else:
+			p.zticks(options.getfieldvalue('zticks'))
+	#}}}
+
+	#xticklabels,yticklabels,zticklabels {{{
+	if options.exist('xticklabels'):
+		xticklabels=options.getfieldvalue('xticklabels')
+		xtickloc=p.xticks()[0]	
+		p.xticks(xtickloc,xticklabels)
+	if options.exist('yticklabels'):
+		yticklabels=options.getfieldvalue('yticklabels')
+		ytickloc=p.yticks()[0]	
+		p.yticks(ytickloc,yticklabels)
+	if options.exist('zticklabels'):
+		zticklabels=options.getfieldvalue('zticklabels')
+		ztickloc=p.zticks()[0]	
+		p.zticks(ztickloc,zticklabels)
+	#}}}
+
+	#ticklabelfontsize {{{
+	if options.exist('ticklabelfontsize'):
+		ax=p.gca()
+		for label in ax.get_xticklabels() + ax.get_yticklabels():
+			label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
+		if int(md.mesh.dimension)==3: 
+			for label in ax.get_zticklabels():
+				label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
+	#}}}
+	#view
+
+	#axis
+
+	#box
+
+	#xlim, ylim, zlim {{{
+	if options.exist('xlim'):
+		p.xlim(options.getfieldvalue('xlim'))
+	if options.exist('ylim'):
+		p.xlim(options.getfieldvalue('ylim'))
+	if options.exist('zlim'):
+		p.xlim(options.getfieldvalue('zlim'))
+	#}}}
+
+	#latlon
+
+	#Basinzoom
+
+	#ShowBasins
+
+	#Caxis
+
+	#shading
+
+	#grid {{{
+	if options.exist('grid'):
+		if 'on' in options.getfieldvalue('grid','on'):
+			p.grid()
+	#}}}
+
+	#colormap
+
+	#wrapping
+
+	#colorbar {{{
+	if 'on' in options.getfieldvalue('colorbar','off'):
+		p.colorbar()
+	#}}}
+
+	#area
+
+	#expdisp
+
+	#text
+
+	#north arrow
+
+	#scale ruler
+
+	#streamlines
+
+	#contours
+
+	#axis positions
+
+	#figure position
+
+	#axes position
+
+	#showregion
+
+	#flat edges of a partition
+
+	#scatter
+
+	#backgroundcolor
+
+	#figurebackgroundcolor
+
+	#lighting
+
+	#point cloud
+
+	#inset
Index: /issm/trunk/src/m/plot/arrow.m
===================================================================
--- /issm/trunk/src/m/plot/arrow.m	(revision 13974)
+++ /issm/trunk/src/m/plot/arrow.m	(revision 13975)
@@ -8,5 +8,4 @@
 %            'ratio': default .5 (ratio headarrow/length)
 %            'widthratio': default is 1/10 of length
-
 
 %recover options
Index: /issm/trunk/src/m/plot/checkplotoptions.m
===================================================================
--- /issm/trunk/src/m/plot/checkplotoptions.m	(revision 13974)
+++ /issm/trunk/src/m/plot/checkplotoptions.m	(revision 13975)
@@ -1,3 +1,3 @@
-function options=checkplotoptions(md,options);
+function options=checkplotoptions(md,options)
 %PARSE_OPTIONS - build a structure that holds all plot options
 %
@@ -53,5 +53,5 @@
 	end
 end
-	
+
 %text
 if exist(options,'text'),
Index: /issm/trunk/src/m/plot/checkplotoptions.py
===================================================================
--- /issm/trunk/src/m/plot/checkplotoptions.py	(revision 13975)
+++ /issm/trunk/src/m/plot/checkplotoptions.py	(revision 13975)
@@ -0,0 +1,15 @@
+def checkplotoptions(md,options):
+	'''
+	CHECKPLOTOPTIONS - build a structure that holds all plot options
+
+		Usage:
+			options=checkplotoptions(md,options)
+
+		See also: PLOTMODEL
+
+		NOTE: not fully implemented yet
+	'''
+
+	print "WARNING: checkplotoptions not implemented: options returned as passed"
+	return options
+
Index: /issm/trunk/src/m/plot/colormaps/getcolormap.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 13974)
+++ /issm/trunk/src/m/plot/colormaps/getcolormap.m	(revision 13975)
@@ -21,5 +21,5 @@
 
 if strcmpi(map,'Ala'),
-	map = jet;
+	map = jet(256);
 	map = map(128:end,:);
 elseif strcmpi(map,'redblue'),
Index: /issm/trunk/src/m/plot/colormaps/haxby.m
===================================================================
--- /issm/trunk/src/m/plot/colormaps/haxby.m	(revision 13974)
+++ /issm/trunk/src/m/plot/colormaps/haxby.m	(revision 13975)
@@ -1,3 +1,3 @@
-function map = haxby(m);
+function map = haxby(m)
 %HAXBY - Haxby color map
 %   HAXBY(M) returns an M-by-3 matrix containing a colormap with Haxby's
Index: /issm/trunk/src/m/plot/curvedarrow.m
===================================================================
--- /issm/trunk/src/m/plot/curvedarrow.m	(revision 13975)
+++ /issm/trunk/src/m/plot/curvedarrow.m	(revision 13975)
@@ -0,0 +1,76 @@
+function curvedarrow(centerx,centery,distance,angle,secondangle,varargin)
+%CURVEDARROW - plot curved arrow, where curvature center is on (centerx,centery), radius is 'distance', 
+%   and angle determines arc length (angle in degrees). secondangle determines by how much the arc 
+%   generated is rotated along the [0,0,1] z axis.30,
+%
+%   Usage:
+%      curevedarrow(x1,y1,r,30,30,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
+%            'width': if you want to specify an absolute width
+
+	%recover options
+	options=pairoptions(varargin{:});
+	ratio=getfieldvalue(options,'ratio',.1);
+	arrowlength=getfieldvalue(options,'arrowlength',1);
+	color=getfieldvalue(options,'color','k');
+
+	%transform angle in radians
+	angle=angle/180*pi;
+	nsteps=10;
+
+	%compute some values out of (x1,y1) and (x2,y2)
+	length=distance*angle;
+	
+	if exist(options,'widthratio'),
+		widthratio=getfieldvalue(options,'widthratio');
+		width=length*widthratio;
+	else if exist(options,'width'),
+		width=getfieldvalue(options,'width');
+	else 
+		widthratio=.1;
+		width=length*widthratio;
+	end
+
+	%buidl the arrow itself: 
+	A=[centerx+distance, centery];
+	B=[centerx+distance+width, centery];
+	BC=[centerx+cos(0:angle/nsteps:angle)*(distance+width); centery+sin(0:angle/nsteps:angle)*(distance+width)]';
+	C=[centerx+cos(angle)*(distance+width), centery+sin(angle)*(distance+width)];
+	D=[centerx+cos(angle)*(distance), centery+sin(angle)*(distance)];
+	DA=[centerx+cos(angle:-angle/nsteps:0)*(distance); centery+sin(angle:-angle/nsteps:0)*(distance)]';
+
+	%Plot arrow
+	hold on
+	p1=patch([A(1) B(1) BC(:,1)' C(1) D(1) DA(:,1)' ],[A(2) B(2) BC(:,2)' C(2) D(2) DA(:,2)'],color);
+	set(p1,'EdgeColor',color); set(p1,'FaceColor',color);
+
+	%Build arrowhead 
+	E=D+2/3*(D-C);
+	F=C+2/3*(C-D);
+
+	n=(F-E)/norm(F-E,2);
+	m=[-n(2) n(1)];
+	if(angle<0)
+		m=-m;
+	end
+	
+	if exist(options,'arrowlength'),
+		d=arrowlength;
+	else
+		d=abs((distance*angle)*ratio);
+	end
+	
+	%G is d distance from middle of E and F: 
+	G=(E+F)/2+d*m;
+
+	p2=patch([E(1) F(1) G(1)],[E(2) F(2) G(2)],color);
+	set(p2,'EdgeColor',color); set(p2,'FaceColor',color);
+
+	%now rotate our arrow: 
+	rotate(p1,[0 0  1],secondangle);
+	rotate(p2,[0 0 1],secondangle);
+
+end
Index: /issm/trunk/src/m/plot/kmlgroundoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 13974)
+++ /issm/trunk/src/m/plot/kmlgroundoverlay.m	(revision 13975)
@@ -1,3 +1,3 @@
-function kmlgroundoverlay(md,options);
+function kmlgroundoverlay(md,options)
 %KMLGROUNDOVERLAY: create ground overlay image in kml format
 %
Index: /issm/trunk/src/m/plot/latlonoverlay.m
===================================================================
--- /issm/trunk/src/m/plot/latlonoverlay.m	(revision 13974)
+++ /issm/trunk/src/m/plot/latlonoverlay.m	(revision 13975)
@@ -117,5 +117,4 @@
 	end
 
-
 	pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
 	if length(pos)<=1, continue; end
Index: /issm/trunk/src/m/plot/plot_BC.m
===================================================================
--- /issm/trunk/src/m/plot/plot_BC.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_BC.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_BC(md,options,width,i,data);
+function plot_BC(md,options,width,i,data)
 
 %plot neuman
Index: /issm/trunk/src/m/plot/plot_basaldrag.m
===================================================================
--- /issm/trunk/src/m/plot/plot_basaldrag.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_basaldrag.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_basaldrag(md,options,width,i,type);
+function plot_basaldrag(md,options,width,i,type)
 
 %PLOT_BASALDRAG - plot basal drag
Index: /issm/trunk/src/m/plot/plot_boundaries.m
===================================================================
--- /issm/trunk/src/m/plot/plot_boundaries.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_boundaries.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_boundaries(md,options,width,i);
+function plot_boundaries(md,options,width,i)
 %PLOT_BOUNDARIES - plot mesh boundaries
 %
Index: /issm/trunk/src/m/plot/plot_contour.m
===================================================================
--- /issm/trunk/src/m/plot/plot_contour.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_contour.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_contour(md,datain,options);
+function plot_contour(md,datain,options)
 %PLOT_CONTOUR - plot contours of a given field
 %
Index: /issm/trunk/src/m/plot/plot_drivingstress.m
===================================================================
--- /issm/trunk/src/m/plot/plot_drivingstress.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_drivingstress.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_drivingstress(md,options,width,i);
+function plot_drivingstress(md,options,width,i)
 %PLOT_DRIVINGSTRESS - plot driving stress
 %
Index: /issm/trunk/src/m/plot/plot_edges.m
===================================================================
--- /issm/trunk/src/m/plot/plot_edges.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_edges.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_edges(md,options,width,i,datai);
+function plot_edges(md,options,width,i,datai)
 %PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
 %
Index: /issm/trunk/src/m/plot/plot_elementnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_elementnumbering.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_elementnumbering(md,options,width,i);
+function plot_elementnumbering(md,options,width,i)
 %PLOT_ELEMENTNUMBERING - plot element numbering
 %
Index: /issm/trunk/src/m/plot/plot_elementstype.m
===================================================================
--- /issm/trunk/src/m/plot/plot_elementstype.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_elementstype.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_elementstype(md,options,width,i);
+function plot_elementstype(md,options,width,i)
 %PLOT_ELEMENTSTYPE - plot elements type
 %
Index: /issm/trunk/src/m/plot/plot_highlightelements.m
===================================================================
--- /issm/trunk/src/m/plot/plot_highlightelements.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_highlightelements.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_highlightelements(md,options,width,i);
+function plot_highlightelements(md,options,width,i)
 %PLOT_HIGHLIGHTELEMENTS - plot selected elements
 %
Index: /issm/trunk/src/m/plot/plot_highlightvertices.m
===================================================================
--- /issm/trunk/src/m/plot/plot_highlightvertices.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_highlightvertices.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_highlightvertices(md,options,width,i);
+function plot_highlightvertices(md,options,width,i)
 %PLOT_HIGHLIGHTVERTICES - plot selected vertices
 %
@@ -21,5 +21,5 @@
 	%Highlight
 	pos=getfieldvalue(options,'highlight',[]);
-	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
 		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
 else
@@ -34,5 +34,5 @@
 	%Highlight
 	pos=getfieldvalue(options,'highlight',[]);
-	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
 		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
 end
Index: /issm/trunk/src/m/plot/plot_icefront.m
===================================================================
--- /issm/trunk/src/m/plot/plot_icefront.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_icefront.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_icefront(md,options,width,i,data);
+function plot_icefront(md,options,width,i,data)
 %PLOT_ICEFRONT - plot segment on neumann BC
 %
Index: /issm/trunk/src/m/plot/plot_importancefactors.m
===================================================================
--- /issm/trunk/src/m/plot/plot_importancefactors.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_importancefactors.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_importancefactors(md,options,width,ii);
+function plot_importancefactors(md,options,width,ii)
 %PLOT_IMPORTANCEFACTORS - plot importance factors
 %
Index: /issm/trunk/src/m/plot/plot_manager.m
===================================================================
--- /issm/trunk/src/m/plot/plot_manager.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_manager.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_manager(md,options,subplotwidth,nlines,ncols,i);
+function plot_manager(md,options,subplotwidth,nlines,ncols,i)
 %PLOT__MANAGER - distribute the plots, called by plotmodel
 %
@@ -33,13 +33,13 @@
 			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);
@@ -118,5 +118,5 @@
 			plot_segments(md,options,subplotwidth,i,data)
 			return
-		
+
 		case 'quiver'
 			data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
@@ -199,5 +199,5 @@
 		error('cannot kmlgroundoverlay on multi-plots');
 	end
-	
+
 	%call routine to build kml file and image that goes with it.
 	kmlgroundoverlay(md,options);
Index: /issm/trunk/src/m/plot/plot_manager.py
===================================================================
--- /issm/trunk/src/m/plot/plot_manager.py	(revision 13975)
+++ /issm/trunk/src/m/plot/plot_manager.py	(revision 13975)
@@ -0,0 +1,67 @@
+
+try:
+	import pylab as p
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+from pairoptions import *
+from checkplotoptions import checkplotoptions
+from plot_mesh import plot_mesh
+from processmesh import processmesh
+from processdata import processdata
+from plot_unit import plot_unit
+from applyoptions import applyoptions
+
+def 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)
+	#print 'options:', options
+
+	#get data to be plotted
+	data=options.getfieldvalue('data');
+
+	#figure out if this is a special plot
+	if isinstance(data,(str,unicode)):
+
+		# convert string to lower case for a case-insensitive comparison
+		if data.lower()=='mesh': 
+			plot_mesh(md,options,nlines,ncols,i)
+			return
+		else:
+			print "WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data
+
+	#elif data in vars(md):
+	#else:
+		#print "'data' not a string, plotting model properties yet to be implemented..."
+
+	#Overlay plot
+
+	#Gridded plot
+
+	#Section plot
+
+	#Profile plot
+
+	#process data and model
+	x,y,z,elements,is2d,isplanet=processmesh(md,data,options)
+	data2,datatype=processdata(md,data,options)
+
+	#standard plot
+	p.subplot(nlines,ncols,i)
+
+	#plot unit
+	plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options)
+
+	#apply all options
+	applyoptions(md,data2,options)
+
+	#ground overlay on kml plot_unit
Index: /issm/trunk/src/m/plot/plot_mesh.m
===================================================================
--- /issm/trunk/src/m/plot/plot_mesh.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_mesh.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_mesh(md,options,nlines,ncols,i);
+function plot_mesh(md,options,nlines,ncols,i)
 %PLOT_MESH - plot model mesh
 %
Index: /issm/trunk/src/m/plot/plot_mesh.py
===================================================================
--- /issm/trunk/src/m/plot/plot_mesh.py	(revision 13975)
+++ /issm/trunk/src/m/plot/plot_mesh.py	(revision 13975)
@@ -0,0 +1,30 @@
+
+try:
+	import pylab as p
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+from processmesh import processmesh
+from applyoptions import applyoptions
+
+def plot_mesh(md,options,nlines,ncols,i):
+	'''
+	PLOT_MESH - plot model mesh
+
+		Usage:
+			plot_mesh(md,options,nlines,ncols,i)
+
+		See also: PLOTMODEL
+	'''
+
+	x,y,z,elements,is2d,isplanet=processmesh(md,[],options)
+
+	if is2d:
+		p.subplot(nlines,ncols,i)
+		p.triplot(x,y,elements)
+	else:
+		print 'WARNING: only 2D mesh plot is currently implemented'
+	
+	#apply options
+	options.addfielddefault('title','Mesh')
+	applyoptions(md,[],options)
Index: /issm/trunk/src/m/plot/plot_none.m
===================================================================
--- /issm/trunk/src/m/plot/plot_none.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_none.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_none(md,options,nlines,ncols,i);
+function plot_none(md,options,nlines,ncols,i)
 %PLOT_NONE - plot nothing, just apply options
 %
Index: /issm/trunk/src/m/plot/plot_overlay.m
===================================================================
--- /issm/trunk/src/m/plot/plot_overlay.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_overlay.m	(revision 13975)
@@ -25,5 +25,4 @@
 	error('buildoverlay error message: overlay not supported for quiver plots');
 end
-
 
 %radar power
@@ -150,5 +149,7 @@
 	options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
 end
-options=addfielddefault(options,'axis','equal off');              % default axis
+options=addfielddefault(options,'xlim',xlim);        % default xlim
+options=addfielddefault(options,'ylim',ylim);        % default ylim
+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 13974)
+++ /issm/trunk/src/m/plot/plot_parthist.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_parthist(md,options,nlines,ncols,i);
+function plot_parthist(md,options,nlines,ncols,i)
 %PLOT_PARTHIST - plot partitioning histogram
 %
Index: /issm/trunk/src/m/plot/plot_parthistn.m
===================================================================
--- /issm/trunk/src/m/plot/plot_parthistn.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_parthistn.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_parthist(md,options,nlines,ncols,i);
+function plot_parthist(md,options,nlines,ncols,i)
 %PLOT_PARTHIST - plot partitioning histogram
 %
Index: /issm/trunk/src/m/plot/plot_parthistw.m
===================================================================
--- /issm/trunk/src/m/plot/plot_parthistw.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_parthistw.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_parthist(md,options,nlines,ncols,i);
+function plot_parthist(md,options,nlines,ncols,i)
 %PLOT_PARTHIST - plot partitioning histogram
 %
Index: /issm/trunk/src/m/plot/plot_penalties.m
===================================================================
--- /issm/trunk/src/m/plot/plot_penalties.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_penalties.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_penalties(md,options,width,i);
+function plot_penalties(md,options,width,i)
 %PLOT_PENALTIES - plot penalties
 %
Index: /issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
+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
 %
@@ -27,5 +27,5 @@
 
 		%plot normals
-		
+
 		for j=1:length(segments),
 			xstart=mean([segments(j,1) segments(j,3)]);
Index: /issm/trunk/src/m/plot/plot_qmuhistnorm.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmuhistnorm.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_qmuhistnorm.m	(revision 13975)
@@ -1,8 +1,7 @@
-function plot_qmuhistnorm(md,options,nlines,ncols,index);
+function plot_qmuhistnorm(md,options,nlines,ncols,index)
 
 %prepare plot
 subplot(nlines,ncols,index); 
 hold on
-
 
 %recover histnorm data
Index: /issm/trunk/src/m/plot/plot_qmumean.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmumean.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_qmumean.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_qmumean(md,options,nlines,ncols,i);
+function plot_qmumean(md,options,nlines,ncols,i)
 %PLOT_QMUMEAN - plot mean of a scaled response 
 %
Index: /issm/trunk/src/m/plot/plot_qmustddev.m
===================================================================
--- /issm/trunk/src/m/plot/plot_qmustddev.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_qmustddev.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_qmustddev(md,options,nlines,ncols,i);
+function plot_qmustddev(md,options,nlines,ncols,i)
 %PLOT_QMUMEAN - plot stddev of a scaled response 
 %
@@ -47,5 +47,4 @@
 end
 
-
 %now, project onto vertices
 responses_on_node=responses(md.qmu.partition+1);
Index: /issm/trunk/src/m/plot/plot_referential.m
===================================================================
--- /issm/trunk/src/m/plot/plot_referential.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_referential.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_referential(md,options,width,i,data);
+function plot_referential(md,options,width,i,data)
 %PLOT_PRESSURELOAD - plot segment on neumann BC
 %
Index: /issm/trunk/src/m/plot/plot_riftfraction.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftfraction.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_riftfraction.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_riftfraction(md,options,nlines,ncols,index);
+function plot_riftfraction(md,options,nlines,ncols,index)
 %PLOT_RIFTFRACTION - plot rift fractions
 %
Index: /issm/trunk/src/m/plot/plot_riftnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftnumbering.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_riftnumbering.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_riftnumbering(md,options,nlines,ncols,index);
+function plot_riftnumbering(md,options,nlines,ncols,index)
 %PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
 %
@@ -88,5 +88,4 @@
 end
 
-
 %apply options
 options=addfielddefault(options,'title','Rift/Fault location');
Index: /issm/trunk/src/m/plot/plot_riftpenetration.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftpenetration.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_riftpenetration.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_rifpenetration(md,options,nlines,ncols,index);
+function plot_rifpenetration(md,options,nlines,ncols,index)
 %PLOT_RIFTPENETRATION - plot rift penetration
 %
Index: /issm/trunk/src/m/plot/plot_riftrelvel.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftrelvel.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_riftrelvel.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_riftrelvel(md,options,nlines,ncols,index);
+function plot_riftrelvel(md,options,nlines,ncols,index)
 %PLOT_RIFTRELVEL - plot rift relative velocities
 %
@@ -15,4 +15,7 @@
 end
 options=addfielddefault(options,'scaling',2);
+
+%markersize: 
+markersize=getfieldvalue(options,'markersize',1);
 
 %recover vx and vy:
@@ -38,9 +41,4 @@
 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=[];
@@ -63,5 +61,5 @@
 end
 for i=1:size(md.rifts.riftstruct,1),
-	
+
 	%get nodes on rift
 	penaltypairs=md.rifts.riftstruct(i).penaltypairs;
@@ -81,8 +79,8 @@
 		%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);
+			p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'.','MarkerSize',markersize); set(p2,'Color',[140 140 140]/255);
 			isp2=1;
 		else
-			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
+			p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k.','MarkerSize',markersize);
 			isp1=1;
 		end
@@ -90,16 +88,19 @@
 
 	%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*');
+	h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g.','MarkerSize',markersize);
+	plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g.','MarkerSize',markersize);
 	segments=md.rifts.riftstruct(i).segments(:,1:2);
 end
+
+faulttitle=getfieldvalue(options','faulttitle','faults');
+rifttitle=getfieldvalue(options','rifttitle','rifts');
 %legend
 if strcmpi(getfieldvalue(options,'legend','on'),'on'),
 	if isp1 & isp2
-		l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
+		l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips',faulttitle,rifttitle);
 	elseif isp1
-		l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
+		l=legend([h1,h2,p1],'mesh boundaries','crack tips',faulttitle);
 	elseif isp2
-		l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
+		l=legend([h1,h2,p2],'mesh boundaries','crack tips',rifttitle);
 	else
 		l=legend([h1,h2],'mesh boundaries','crack tips');
Index: /issm/trunk/src/m/plot/plot_rifts.m
===================================================================
--- /issm/trunk/src/m/plot/plot_rifts.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_rifts.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_rifts(md,options,nlines,ncols,index);
+function plot_rifts(md,options,nlines,ncols,index)
 %PLOT_RIFTS - plot rifts in a mesh
 %
@@ -16,5 +16,5 @@
 offset=getfieldvalue(options,'offset',500);
 if isstruct(md.rifts.riftstruct),
-	
+
 	for i=1:size(md.rifts.riftstruct,1),
 		penaltypairs=md.rifts.riftstruct(i).penaltypairs;
Index: /issm/trunk/src/m/plot/plot_riftvel.m
===================================================================
--- /issm/trunk/src/m/plot/plot_riftvel.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_riftvel.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_riftvel(md,options,nlines,ncols,index);
+function plot_riftvel(md,options,nlines,ncols,index)
 %PLOT_RIFTVEL - plot rift velocity
 %
@@ -89,5 +89,4 @@
 end
 
-
 %legend
 if isp1 & isp2
Index: /issm/trunk/src/m/plot/plot_sarpwr.m
===================================================================
--- /issm/trunk/src/m/plot/plot_sarpwr.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_sarpwr.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_sarpwr(md,options,width,i);
+function plot_sarpwr(md,options,width,i)
 %PLOT_SARPWR - plot radar image
 %
@@ -17,5 +17,5 @@
 	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);
 
Index: /issm/trunk/src/m/plot/plot_scatter.m
===================================================================
--- /issm/trunk/src/m/plot/plot_scatter.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_scatter.m	(revision 13975)
@@ -1,5 +1,5 @@
-function plot_scatter(x,y,level,options),
+function plot_scatter(x,y,level,varargin),
 
-if nargin==3, options=pairoptions(); end
+options=pairoptions(varargin{:}); 
 
 %check input
@@ -13,4 +13,6 @@
 Siz=length(level);
 nlab=10;
+%Min=0;
+%Max=1300;
 
 %OK, should we create a new colorbar for the occasion?
Index: /issm/trunk/src/m/plot/plot_section.m
===================================================================
--- /issm/trunk/src/m/plot/plot_section.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_section.m	(revision 13975)
@@ -115,5 +115,4 @@
 			hold on
 
-
 			%3D
 		else
Index: /issm/trunk/src/m/plot/plot_segments.m
===================================================================
--- /issm/trunk/src/m/plot/plot_segments.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_segments.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_segments(md,options,width,i,datai);
+function plot_segments(md,options,width,i,datai)
 %PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
 %
@@ -42,5 +42,4 @@
 	h3=plot(xstart,ystart,'r*');
 
-
 else
 	error('plot_segments: 3d plot of segments not supported yet!');
Index: /issm/trunk/src/m/plot/plot_tensor.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_tensor.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_tensor(md,options,width,i,type);
+function plot_tensor(md,options,width,i,type)
 %PLOT_TENSOR - plot tensor components
 %
Index: /issm/trunk/src/m/plot/plot_tensor_components.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_components.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_tensor_components.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_tensor_components(md,options,width,i,tensor,type,plot_options);
+function plot_tensor_components(md,options,width,i,tensor,type,plot_options)
 %PLOT_TENSOR_COMPONENT - plot component of a tensor
 %
Index: /issm/trunk/src/m/plot/plot_tensor_principal.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_principal.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_tensor_principal.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
+function plot_tensor_principal(md,options,width,i,tensor,type,plot_options)
 %PLOT_TENSOR_PRINCIPAL - plot principal values
 %
Index: /issm/trunk/src/m/plot/plot_tensor_principalaxis.m
===================================================================
--- /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_tensor_principalaxis.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
+function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options)
 %PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
 %
Index: /issm/trunk/src/m/plot/plot_thermaltransient_results.m
===================================================================
--- /issm/trunk/src/m/plot/plot_thermaltransient_results.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_thermaltransient_results.m	(revision 13975)
@@ -22,3 +22,2 @@
 eval(string);
 clear string;
-
Index: /issm/trunk/src/m/plot/plot_transient_movie.m
===================================================================
--- /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_transient_movie.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_transient_movie(md,options,width,i);
+function plot_transient_movie(md,options,width,i)
 %PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
 %   Usage:
Index: /issm/trunk/src/m/plot/plot_unit.py
===================================================================
--- /issm/trunk/src/m/plot/plot_unit.py	(revision 13975)
+++ /issm/trunk/src/m/plot/plot_unit.py	(revision 13975)
@@ -0,0 +1,53 @@
+
+try:
+	import pylab as p
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+def 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=options.getfieldvalue('edgecolor','None')
+
+	#number of colorlevels for plots
+	colorlevels=options.getfieldvalue('colorlevels',256)
+
+	if datatype==1:
+		#element plot
+		if is2d:
+			p.tripcolor(x,y,elements,data,colorlevels)
+		else:
+			raise ValueError('plot_unit error: 3D element plot not supported yet')
+		return
+
+	elif datatype==2:
+		#node plot
+		if is2d:
+			p.tricontourf(x,y,elements,data,colorlevels)
+		else:
+			raise ValueError('plot_unit error: 3D node plot not supported yet')
+		return
+
+	elif datatype==3:
+		print 'plot_unit message: quiver plot not implemented yet'
+		return
+
+	elif datatype==4:
+		#P1 patch plot
+		print 'plot_unit message: P1 patch plot not implemented yet'
+		return
+
+	elif datatype==5:
+		print 'plot_unit message: P0 patch plot not implemented yet'
+		return
+
+	else:
+		raise ValueError('datatype=%d not supported' % datatype)
Index: /issm/trunk/src/m/plot/plot_vertexnumbering.m
===================================================================
--- /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plot_vertexnumbering.m	(revision 13975)
@@ -1,3 +1,3 @@
-function plot_vertexnumbering(md,options,width,i);
+function plot_vertexnumbering(md,options,width,i)
 %PLOT_VERTEXNUMBERING - plot vertex numbering
 %
@@ -25,5 +25,5 @@
 	%Highlight
 	pos=getfieldvalue(options,'highlight',[]);
-	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
 		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
 else
@@ -42,5 +42,5 @@
 	%Highlight
 	pos=getfieldvalue(options,'highlight',[]);
-	text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
+	text(x(pos),y(pos),z(pos),num2str(pos(:)),...
 		'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
 end
Index: /issm/trunk/src/m/plot/plotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.m	(revision 13974)
+++ /issm/trunk/src/m/plot/plotmodel.m	(revision 13975)
@@ -32,5 +32,5 @@
 %go through subplots
 if numberofplots,
-		
+
 	%Create figure 
 	if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
Index: /issm/trunk/src/m/plot/plotmodel.py
===================================================================
--- /issm/trunk/src/m/plot/plotmodel.py	(revision 13975)
+++ /issm/trunk/src/m/plot/plotmodel.py	(revision 13975)
@@ -0,0 +1,67 @@
+
+try:
+	import pylab as p
+except ImportError:
+	print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
+
+#from pairoptions import *
+from plotoptions import plotoptions
+from plot_manager import plot_manager
+from math import ceil, sqrt
+
+def plotmodel(md,*args):
+	'''
+	at command prompt, type 'plotdoc' for additional documentation
+	'''
+
+	#First process options 
+	options=plotoptions(*args)
+
+	#get number of subplots
+	subplotwidth=ceil(sqrt(options.numberofplots))
+	
+	#if nlines and ncols specified, then bypass
+	if options.list[0].exist('nlines'):
+		nlines=options.list[0].getfieldvalue('nlines')
+		nl=True
+	else:
+		nlines=subplotwidth
+		nl=False
+	
+	if options.list[0].exist('ncols'):
+		ncols=options.list[0].getfieldvalue('ncols')
+		nc=True
+	else:
+		ncols=subplotwidth
+		nc=False
+	
+	#check that nlines and ncols were given at the same time!
+	if not nl==nc:
+		raise StandardError('error: nlines and ncols need to be specified together, or not at all')
+	
+	#Get figure number and number of plots
+	figurenumber=options.figurenumber
+	numberofplots=options.numberofplots
+	
+	#Go through plots
+	if numberofplots:
+		
+		#Create figure
+		#plots will be visible by default if ipython is run in interactive mode (invoked by ipython --pylab)
+		#handling the 'visible' option will need some check on whether ipython is currently in interactive or non-interactive mode
+
+		#if figsize specified
+		if options.list[0].exist('figsize'):
+			figsize=options.list[0].getfieldvalue('figsize')
+			p.figure(figurenumber,figsize=figsize)
+		else:
+			p.figure(figurenumber)
+			
+		#try:
+		for i in xrange(numberofplots):
+			plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],subplotwidth,nlines,ncols,i)
+		#except StandardError:
+		#	print 'error in plot_manager'
+	else:
+		raise StandardError('plotmodel error message: no output data found.')
+			
Index: /issm/trunk/src/m/plot/processdata.m
===================================================================
--- /issm/trunk/src/m/plot/processdata.m	(revision 13974)
+++ /issm/trunk/src/m/plot/processdata.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [data datatype]=processdata(md,data,options);
+function [data datatype]=processdata(md,data,options)
 %PROCESSDATA - process data to be plotted
 %
@@ -48,8 +48,8 @@
 end
 
-%get datatype
+%get datasize
 datasize=size(data);
 
-%Process NaN if any (do not now before mask is applied)
+%Process NaN if any (do not know before mask is applied)
 if exist(options,'nan')
 	data(find(isnan(data)))=getfieldvalue(options,'nan',0);
@@ -74,5 +74,5 @@
 		error('plotmodel error message: data not supported yet');
 	end
-	
+
 	%quiver?
 	if datasize(2)>1,
Index: /issm/trunk/src/m/plot/processdata.py
===================================================================
--- /issm/trunk/src/m/plot/processdata.py	(revision 13975)
+++ /issm/trunk/src/m/plot/processdata.py	(revision 13975)
@@ -0,0 +1,79 @@
+from math import isnan
+import numpy as npy
+
+def 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 (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and isnan(data).all())):
+		raise ValueError("processdata error message: 'data' provided is empty")
+
+	#needed later on
+	if md.mesh.numberofvertices2d:
+		numberofvertices2d=md.mesh.numberofvertices2d
+		numberofelements2d=md.mesh.numberofelements2d
+	else:
+		numberofvertices2d=npy.nan
+		numberofelements2d=npy.nan
+
+	#process patch
+
+	#initialize datatype
+	datatype=0
+
+	#get datasize
+	if npy.ndim(data)==1:
+		datasize=npy.array([len(data),1])
+	else:
+		datasize=npy.shape(data)
+	
+	#process NaN's if any
+	if options.exist('nan'):
+		data[npy.isnan(data)]=options.getfieldvalue('nan',0)
+
+	#non-patch processing 
+
+	#element data
+	if datasize[0]==md.mesh.numberofelements and datasize[1]==1:
+		
+		#initialize datatype if non patch
+		if datatype!=4 and datatype!=5:
+			datatype=1
+
+		#mask?
+
+		#log?
+
+	#node data
+	if datasize[0]==md.mesh.numberofvertices and datasize[1]==1:
+		datatype=2
+
+		#mask?
+
+		#log?
+
+	#layer projection?
+
+	#control arrow density if quiver plot
+
+	#convert rank-2 array to rank-1
+	if npy.ndim(data)==2 and npy.shape(data)[1]==1:
+		data=data.reshape(-1,)
+
+	#if datatype is still zero, error out
+	if datatype==0:
+		raise ValueError("processdata error: data provided not recognized or not supported")
+	else:
+		return data, datatype
Index: /issm/trunk/src/m/plot/processmesh.m
===================================================================
--- /issm/trunk/src/m/plot/processmesh.m	(revision 13974)
+++ /issm/trunk/src/m/plot/processmesh.m	(revision 13975)
@@ -1,3 +1,3 @@
-function [x y z elements is2d isplanet]=processmesh(md,data,options);
+function [x y z elements is2d isplanet]=processmesh(md,data,options)
 %PROCESSMESH - process mesh to be plotted
 %
@@ -36,5 +36,4 @@
 		z=md.mesh.z;
 	end
-
 
 	if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
Index: /issm/trunk/src/m/plot/processmesh.py
===================================================================
--- /issm/trunk/src/m/plot/processmesh.py	(revision 13975)
+++ /issm/trunk/src/m/plot/processmesh.py	(revision 13975)
@@ -0,0 +1,87 @@
+from math import isnan
+
+def processmesh(md,data,options):
+	"""
+	PROCESSMESH - process the mesh for plotting
+
+	Usage:
+		[x y z elements is2d]=processmech(md,data,options)
+
+	See also: PLOTMODEL, PROCESSDATA
+	"""
+
+	#some checks
+	if md.mesh.numberofvertices==0:
+		raise ValueError('processmesh error: mesh is empty')
+	if md.mesh.numberofvertices==md.mesh.numberofelements:
+		raise ValueError('processmesh error: the number of elements is the same as the number of nodes')
+
+	if len(data)==0 or not isinstance(data,dict):
+		
+		if 'latlon' not in options.getfieldvalue('coord','xy').lower(): #convert to lower case for comparison
+			x=md.mesh.x
+			if not isnan(md.mesh.x2d): x2d=md.mesh.x2d
+			y=md.mesh.y
+			if not isnan(md.mesh.y2d): y2d=md.mesh.y2d
+		else:
+			x=md.mesh.long
+			y=md.mesh.lat
+
+		z_field=options.getfieldvalue('z',md.mesh.z)
+		#if isinstance(z_field,basestring): # how could z be a string?
+		#	z=md.(z_field)
+		if isinstance(z_field,(int,long,float)):  # isnumeric
+			z=z_field
+		else:
+			z=md.mesh.z
+		
+		if not isnan(md.mesh.elements2d): 
+			elements2d=md.mesh.elements2d
+			elements2d=elements2d-1
+		# subtract one since python indexes from zero
+		elements=md.mesh.elements
+		elements=elements-1
+
+		#is it a 2D plot?
+		if md.mesh.dimension==2:
+			is2d=1
+		elif md.mesh.dimension==3:
+			if options.getfieldvalue('layer',0)>=1:
+				is2d=1
+			else:
+				is2d=0
+		else:
+			raise ValueError('processmesh error: dim = %d not supported' % md.mesh.dimension)
+
+		#layer projection?
+		if options.getfieldvalue('layer',0)>=1:
+			 if 'latlon' in options.getfieldvalue('coord','xy').lower():
+				 raise ValueError('processmesh error: cannot work with 3D mesh in lat-lon coords')
+			#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
+	
+	else:
+		#Process mesh for plotting 
+		if md.mesh.dimension==2:
+			is2d=1
+		else:
+			# process polycollection here for 3D plot
+			is2d=0
+	
+	#units
+	if options.exist('unit'):
+		unit=options.getfieldvalue('unit')
+		x=x*unit
+		y=y*unit
+		z=z*unit
+
+	#is model a member of planet class? (workaround until planet class defined)
+	if md.__class__.__name__!='model':
+		isplanet=1
+	else:
+		isplanet=0
+
+	return x,y,z,elements,is2d,isplanet
Index: /issm/trunk/src/m/plot/quiver_colorbar.m
===================================================================
--- /issm/trunk/src/m/plot/quiver_colorbar.m	(revision 13974)
+++ /issm/trunk/src/m/plot/quiver_colorbar.m	(revision 13975)
@@ -31,5 +31,5 @@
 	fontsize=getfieldvalue(options,'fontsize',14);
 	set(hcb,'FontSize',fontsize);
-	
+
 	if exist(options,'colorbartitle'),
 		backup=gca;
Index: /issm/trunk/src/m/plot/radarpower.m
===================================================================
--- /issm/trunk/src/m/plot/radarpower.m	(revision 13974)
+++ /issm/trunk/src/m/plot/radarpower.m	(revision 13975)
@@ -32,12 +32,12 @@
 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.']);
+		%if ~exist(['/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg']),
+		%	error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg not found.']);
 		%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/ModelData/MOG/' name '.jpg'];
+		%geom=load(['/u/astrid-r1b/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');
@@ -65,13 +65,13 @@
 		%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.']);
+			if ~exist(['/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif']),
+				error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif not found.']);
 			end
-			geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog100_r2_hp1.tif'];
+			geotiff_name=['/u/astrid-r1b/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.']);
+			if ~exist(['/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif']),
+				error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif not found.']);
 			end
-			geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog500_r2_hp1.tif'];
+			geotiff_name=['/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif'];
 		end
 
@@ -90,16 +90,15 @@
 		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.']);
+			if ~exist(['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
+				error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
 			end
-			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
+			geotiff_name=['/u/astrid-r1b/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.']);
+			if ~exist(['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
+				error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
 			end
-			geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
+			geotiff_name=['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
 		end
 
Index: /issm/trunk/src/m/plot/subplotmodel.m
===================================================================
--- /issm/trunk/src/m/plot/subplotmodel.m	(revision 13974)
+++ /issm/trunk/src/m/plot/subplotmodel.m	(revision 13975)
@@ -1,3 +1,3 @@
-function ha=subplotmodel(nlines,ncols,num,options);
+function ha=subplotmodel(nlines,ncols,num,options)
 %SUBPLOTMODEL -  tight subplot that includes margins
 %
Index: /issm/trunk/src/m/print/printmodel.m
===================================================================
--- /issm/trunk/src/m/print/printmodel.m	(revision 13974)
+++ /issm/trunk/src/m/print/printmodel.m	(revision 13975)
@@ -23,5 +23,4 @@
 %      printmodel('image','tiff')
 %      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
-
 
 %get options: 
@@ -54,5 +53,4 @@
 %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.
Index: /issm/trunk/src/m/qmu/MassFluxProcessProfile.m
===================================================================
--- /issm/trunk/src/m/qmu/MassFluxProcessProfile.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/MassFluxProcessProfile.m	(revision 13975)
@@ -1,3 +1,3 @@
-function segments=MassFluxProcessProfile(md,directory,profilename);
+function segments=MassFluxProcessProfile(md,directory,profilename)
 %MASSFLUXPROCESSPROFILE: process an argus domain outlien profile into a list of segments.
 %
@@ -7,5 +7,4 @@
 % See also: PROCESS_QMU_RESPONSE_DATA, PREQMU
 
-
 %first read the profile points.
 profile=expread([directory '/' profilename]);
Index: /issm/trunk/src/m/qmu/dakota_cdfs.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_cdfs.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_cdfs.m	(revision 13975)
@@ -136,7 +136,7 @@
         end
     end
-    
+
     varargout{1}=dresp;
-    
+
 elseif exist('samp','var') && ~isempty(samp)
     cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),...
@@ -147,7 +147,7 @@
             resp,prob,rel,grel);
     end
-    
+
     varargout{1}=cdf;
-    
+
 elseif exist('mean','var'  ) && ~isempty(mean  ) && ...
        exist('stddev','var') && ~isempty(stddev)
@@ -159,5 +159,5 @@
             resp,prob,rel,grel);
     end
-    
+
     varargout{1}=cdf;
 else
@@ -178,5 +178,5 @@
     mu   =mean(samp);
     sigma=std(samp);
-    
+
     cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),4);
     cdf(:,:)=NaN;
Index: /issm/trunk/src/m/qmu/dakota_in_data.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_in_data.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_in_data.m	(revision 13975)
@@ -88,5 +88,4 @@
 % dmeth=dmeth_params_merge(dmeth,dparams)
 
-
 %%  variables
 
@@ -99,5 +98,5 @@
 
 end
-    
+
 %%  responses
 
Index: /issm/trunk/src/m/qmu/dakota_in_params.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_in_params.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_in_params.m	(revision 13975)
@@ -209,3 +209,2 @@
 
 end
-
Index: /issm/trunk/src/m/qmu/dakota_in_parse.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_in_parse.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_in_parse.m	(revision 13975)
@@ -42,5 +42,5 @@
 %
 function [method,dvar,dresp]=dakota_in_parse(filei)
-    
+
 if ~nargin
     help dakota_in_parse
@@ -631,5 +631,5 @@
 
 itoken=itoken+1;
-    
+
 %  read next line if necessary
 
@@ -644,5 +644,5 @@
     itoken=1;
 end
-    
+
 end
 
@@ -668,5 +668,5 @@
     itoken=1;
 end
-    
+
 %  check for equal sign and skip
 
Index: /issm/trunk/src/m/qmu/dakota_moments.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_moments.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_moments.m	(revision 13975)
@@ -89,7 +89,7 @@
             moments_calc(dresp(i).sample,alpha);
     end
-    
+
     varargout{1}=dresp;
-    
+
 elseif exist('samp','var') && ~isempty(samp)
     mean    =zeros(1,size(samp,2));
@@ -106,5 +106,5 @@
             moments_calc(samp(:,i),alpha);
     end
-    
+
     varargout{1}=mean;
     varargout{2}=stddev;
Index: /issm/trunk/src/m/qmu/dakota_out_parse.m
===================================================================
--- /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/dakota_out_parse.m	(revision 13975)
@@ -170,5 +170,5 @@
 end
 display(sprintf('Number of columns (Dakota V+R)=%d.',ntokens-1));
-    
+
 %  process rows of matrix
 
@@ -301,5 +301,5 @@
     end
     [ntokens,tokens]=fltokens(fline);
-    
+
 %  add new response function and moments
 
@@ -336,5 +336,5 @@
     end
     [ntokens,tokens]=fltokens(fline);
-   
+
 %  find response function associated with confidence intervals
 
@@ -464,9 +464,9 @@
     cmat.row   =cell(1,1);
     cmat.matrix=zeros(1,ntokens);
-    
+
     for i=1:ntokens
         cmat.column(1,i)=cellstr(tokens{1}{i});
     end
-    
+
 %  process rows of matrix, reading until blank line
 
@@ -583,5 +583,5 @@
             display(sprintf('  %s',dresp(idresp).descriptor));
         end
-    
+
 %  skip column headings of cdf
 
Index: /issm/trunk/src/m/qmu/examples/direct.m
===================================================================
--- /issm/trunk/src/m/qmu/examples/direct.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/examples/direct.m	(revision 13975)
@@ -4,6 +4,4 @@
 md.qmu.params.evaluation_concurrency=1;
 
-
-
 %or for matlab direct driver
 md.qmu.params.direct=true;
Index: /issm/trunk/src/m/qmu/examples/lrel_mmf.m
===================================================================
--- /issm/trunk/src/m/qmu/examples/lrel_mmf.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/examples/lrel_mmf.m	(revision 13975)
@@ -93,3 +93,2 @@
 %part_hist(md.qmu.partition,md.vertex_weight)
 %plotmodel(md,'data',log10(md.results.dakota.dresp_out(9).impfac(md.qmu.partition+1)))
-
Index: /issm/trunk/src/m/qmu/expandvariables.m
===================================================================
--- /issm/trunk/src/m/qmu/expandvariables.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/expandvariables.m	(revision 13975)
@@ -4,5 +4,5 @@
 
 for i=1:length(fnames)
-    
+
 %  for linear constraints, just copy
 
Index: /issm/trunk/src/m/qmu/importancefactors.m
===================================================================
--- /issm/trunk/src/m/qmu/importancefactors.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/importancefactors.m	(revision 13975)
@@ -8,5 +8,4 @@
 %   Example: factors=importancefactors(md,'drag','max_vel');
 %
-
 
 variablenamelength=length(variablename);
Index: /issm/trunk/src/m/qmu/lclist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/lclist_write.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/lclist_write.m	(revision 13975)
@@ -60,3 +60,2 @@
 
 end
-
Index: /issm/trunk/src/m/qmu/plot/plot_boxplot.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_boxplot.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_boxplot.m	(revision 13975)
@@ -62,5 +62,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -68,5 +68,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -84,5 +84,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -119,5 +119,5 @@
     iarg=iarg+2;
 end
-    
+
 %%  draw the plot
 
Index: /issm/trunk/src/m/qmu/plot/plot_cdf.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_cdf.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_cdf.m	(revision 13975)
@@ -77,5 +77,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -188,5 +188,5 @@
     set(hl1(i),'Color',cmap(imap,:))
 end
-    
+
 xlim('auto')
 [xlims]=xlim;
@@ -278,5 +278,5 @@
         end
     end
-    
+
     if strcmpi(pdfplt,'line')
         xplot=xpdf;
Index: /issm/trunk/src/m/qmu/plot/plot_hist_norm.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_hist_norm.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_hist_norm.m	(revision 13975)
@@ -89,5 +89,5 @@
     dresp1=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -95,5 +95,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp1));
     lsamp=zeros(1,length(dresp1));
@@ -111,5 +111,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     lsamp(1:size(sampr,2))=size(sampr,1);
 
@@ -142,5 +142,5 @@
         iarg=iarg+1;
     end
-    
+
     mu   =zeros(1,length(dresp2));
     sigma=zeros(1,length(dresp2));
@@ -298,5 +298,5 @@
     end
 end
-    
+
 xlim('auto')
 [xlims]=xlim;
Index: /issm/trunk/src/m/qmu/plot/plot_hist_norm_ci.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_hist_norm_ci.m	(revision 13975)
@@ -78,5 +78,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -84,5 +84,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -92,5 +92,5 @@
     sampr=zeros(max(lsamp),length(dresp));
     sampr(:,:)=NaN;
-    
+
     mu     =zeros(1,length(dresp));
     sigma  =zeros(1,length(dresp));
@@ -109,5 +109,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     lsamp(1:size(sampr,2))=size(sampr,1);
 
@@ -121,5 +121,5 @@
         descr=cell(1,size(sampr,2));
     end
-    
+
     mu     =zeros(1,size(sampr,2));
     sigma  =zeros(1,size(sampr,2));
@@ -325,5 +325,5 @@
     end
 end
-    
+
 xlim('auto')
 [xlims]=xlim;
Index: /issm/trunk/src/m/qmu/plot/plot_if_bars.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_if_bars.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_if_bars.m	(revision 13975)
@@ -66,5 +66,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -72,5 +72,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lifr =zeros(1,length(dresp));
@@ -125,5 +125,5 @@
     end
     clear ifmean
-    
+
     dvar=dvar(index);
     ifr =ifr (:,index);
@@ -136,9 +136,9 @@
     dvar(nif+1,1)=cellstr(sprintf('others < %f',ifmin));
     ifr (:,nif+1)=0.;
-    
+
     nif2=0;
     dvar2=cell (size(dvar));
     ifr2 =zeros(size(ifr ));
-    
+
 %  sum filtered rows and copy unfiltered rows
 
@@ -152,10 +152,10 @@
         end
     end
-    
+
 %  copy sums
 
     dvar2(nif2+1)  =dvar(nif+1);
     ifr2 (:,nif2+1)=ifr (:,nif+1);
-    
+
 %  copy back and truncate filtered rows
 
Index: /issm/trunk/src/m/qmu/plot/plot_if_spec.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_if_spec.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_if_spec.m	(revision 13975)
@@ -72,5 +72,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -78,5 +78,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lifr =zeros(1,length(dresp));
@@ -137,5 +137,5 @@
     end
     clear ifmean
-    
+
     dvar=dvar(index);
     ifr =ifr (:,index);
@@ -148,9 +148,9 @@
     dvar(nif+1,1)=cellstr(sprintf('others < %f',ifmin));
     ifr (:,nif+1)=0.;
-    
+
     nif2=0;
     dvar2=cell (size(dvar));
     ifr2 =zeros(size(ifr ));
-    
+
 %  sum filtered rows and copy unfiltered rows
 
@@ -164,10 +164,10 @@
         end
     end
-    
+
 %  copy sums
 
     dvar2(nif2+1)  =dvar(nif+1);
     ifr2 (:,nif2+1)=ifr (:,nif+1);
-    
+
 %  copy back and truncate filtered rows
 
Index: /issm/trunk/src/m/qmu/plot/plot_normdist_bars.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_normdist_bars.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_normdist_bars.m	(revision 13975)
@@ -73,5 +73,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -82,5 +82,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -92,5 +92,5 @@
         descr=cell(1:size(sampr,2));
     end
-    
+
     dresp=struct([]);
     for i=1:size(sampr,2)
Index: /issm/trunk/src/m/qmu/plot/plot_normplot.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_normplot.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_normplot.m	(revision 13975)
@@ -62,5 +62,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -68,5 +68,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -84,5 +84,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -119,5 +119,5 @@
     iarg=iarg+2;
 end
-    
+
 %%  draw the plot
 
Index: /issm/trunk/src/m/qmu/plot/plot_prob_bars.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_prob_bars.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_prob_bars.m	(revision 13975)
@@ -57,5 +57,4 @@
 %%  assemble the data into a matrix and calculate the increments
 
-
 %%  process input data and assemble into matrices and increments
 
@@ -66,5 +65,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -72,5 +71,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lcdfr=zeros(1,length(dresp));
Index: /issm/trunk/src/m/qmu/plot/plot_rlev_bars.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_rlev_bars.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_rlev_bars.m	(revision 13975)
@@ -62,5 +62,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -68,5 +68,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lcdfr=zeros(1,length(dresp));
Index: /issm/trunk/src/m/qmu/plot/plot_rlev_bars_ci.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_rlev_bars_ci.m	(revision 13975)
@@ -74,5 +74,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -83,5 +83,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -93,5 +93,5 @@
         descr=cell(1:size(sampr,2));
     end
-    
+
     dresp=struct([]);
     for i=1:size(sampr,2)
@@ -136,5 +136,5 @@
         display('Using calculated normal fits from sample data.')
     end
-    
+
     if ~isfield(dresp(i),'cdf') || isempty(dresp(i).cdf)
 %  use minus/plus integer standard deviations
Index: /issm/trunk/src/m/qmu/plot/plot_rvsv_line.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_rvsv_line.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_rvsv_line.m	(revision 13975)
@@ -74,5 +74,5 @@
     dvar=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -80,5 +80,5 @@
         iarg=iarg+1;
     end
-    
+
     descv=cell (1,length(dvar));
     lsamp=zeros(1,length(dvar));
@@ -96,5 +96,5 @@
     sampv=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descv=varargin{iarg};
@@ -119,5 +119,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -125,5 +125,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -141,5 +141,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -177,5 +177,5 @@
     iarg=iarg+2;
 end
-    
+
 if     ~exist('nplotr','var') && ~exist('nplotc','var')
     nplotr=1;
@@ -225,5 +225,5 @@
                 'IconDisplayStyle','off'); % Exclude line from legend
         end
-        
+
 %  add the annotation
 
Index: /issm/trunk/src/m/qmu/plot/plot_rvsv_scat3.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_rvsv_scat3.m	(revision 13975)
@@ -79,5 +79,5 @@
     dvar=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -85,5 +85,5 @@
         iarg=iarg+1;
     end
-    
+
     descv=cell (1,length(dvar));
     lsamp=zeros(1,length(dvar));
@@ -101,5 +101,5 @@
     sampv=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descv=varargin{iarg};
@@ -128,5 +128,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -134,5 +134,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -150,5 +150,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -187,5 +187,5 @@
     iarg=iarg+2;
 end
-    
+
 if     ~exist('nplotr','var') && ~exist('nplotc','var')
     nplotr=ceil(sqrt(size(sampr,2)));
@@ -208,5 +208,5 @@
 
 for iresp=1:size(sampr,2)
-    
+
 %  initialize the subplot
 
Index: /issm/trunk/src/m/qmu/plot/plot_rvsv_surf.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_rvsv_surf.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_rvsv_surf.m	(revision 13975)
@@ -76,5 +76,5 @@
     dvar=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -82,5 +82,5 @@
         iarg=iarg+1;
     end
-    
+
     descv=cell (1,length(dvar));
     lsamp=zeros(1,length(dvar));
@@ -98,5 +98,5 @@
     sampv=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descv=varargin{iarg};
@@ -125,5 +125,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -131,5 +131,5 @@
         iarg=iarg+1;
     end
-    
+
     descr=cell (1,length(dresp));
     lsamp=zeros(1,length(dresp));
@@ -147,5 +147,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -184,5 +184,5 @@
     iarg=iarg+2;
 end
-    
+
 if     ~exist('nplotr','var') && ~exist('nplotc','var')
     nplotr=ceil(sqrt(size(sampr,2)));
@@ -208,5 +208,5 @@
         z(ixi(i),iyi(i))=sampr(i,iresp);
     end
-    
+
 %  initialize the subplot
 
Index: /issm/trunk/src/m/qmu/plot/plot_sampdist_bars.m
===================================================================
--- /issm/trunk/src/m/qmu/plot/plot_sampdist_bars.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/plot/plot_sampdist_bars.m	(revision 13975)
@@ -72,5 +72,5 @@
     dresp=varargin{iarg};
     iarg=iarg+1;
-    
+
 %     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
     if iarg <= nargin && iscell(varargin{iarg})
@@ -81,5 +81,5 @@
     sampr=varargin{iarg};
     iarg=iarg+1;
-    
+
     if     iarg <= nargin && iscell(varargin{iarg})
         descr=varargin{iarg};
@@ -91,5 +91,5 @@
         descr=cell(1:size(sampr,2));
     end
-    
+
     dresp=struct([]);
     for i=1:size(sampr,2)
Index: /issm/trunk/src/m/qmu/process_qmu_options.m
===================================================================
--- /issm/trunk/src/m/qmu/process_qmu_options.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/process_qmu_options.m	(revision 13975)
@@ -99,3 +99,2 @@
 outoptions.iparams=iparams;
 outoptions.runmpi=runmpi;
-
Index: /issm/trunk/src/m/qmu/process_qmu_response_data.m
===================================================================
--- /issm/trunk/src/m/qmu/process_qmu_response_data.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/process_qmu_response_data.m	(revision 13975)
@@ -5,5 +5,4 @@
 %
 % See also PREQMU, PRESOLVE
-
 
 %preliminary data
@@ -22,5 +21,4 @@
 end
 
-
 %deal with mass flux profiles
 if process_mass_flux_profiles,
@@ -30,5 +28,5 @@
 		error('process_qmu_response_data error message: could not find a mass_flux exp profile!');
 	end
-	
+
 	if ~iscell(md.qmu.mass_flux_profiles),
 		error('process_qmu_response_data error message: qmu_mass_flux_profiles field should be a cell array of domain outline names');
Index: /issm/trunk/src/m/qmu/qmu_correlation.m
===================================================================
--- /issm/trunk/src/m/qmu/qmu_correlation.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/qmu_correlation.m	(revision 13975)
@@ -12,5 +12,5 @@
 	error('qmu_correlation error message: could not find dresp_dat field in dakota results. you need to run montecarlo before computing correlations');
 end
-	
+
 data=md.qmu.results.dresp_dat;
 
Index: /issm/trunk/src/m/qmu/qmuisdistributed.m
===================================================================
--- /issm/trunk/src/m/qmu/qmuisdistributed.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/qmuisdistributed.m	(revision 13975)
@@ -1,5 +1,4 @@
 function found=qmuisdistribted(string)
 %QMUISDISTRIBTED - figure out if a string is a decriptor with a numerical postfix. Like thickness1, or drag10
-
 
 %just take last string element, and see if it is numeric.
Index: /issm/trunk/src/m/qmu/qmumarshall.m
===================================================================
--- /issm/trunk/src/m/qmu/qmumarshall.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/qmumarshall.m	(revision 13975)
@@ -47,5 +47,5 @@
 	end
 end
-			
+
 if qmu_segments,
 	WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
@@ -57,5 +57,4 @@
 	WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
 end
-
 
 %write part and npart to disk
@@ -71,5 +70,5 @@
 end
 
-function qmumarshallusage();
+function qmumarshallusage()
 disp(' ');
 disp('function qmumarshall(md.qmu.variables,responses)');
Index: /issm/trunk/src/m/qmu/qmuresponse.m
===================================================================
--- /issm/trunk/src/m/qmu/qmuresponse.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/qmuresponse.m	(revision 13975)
@@ -114,3 +114,2 @@
 	error(['qmuresponse error message: unknown descriptor ' descriptor]);
 end
-
Index: /issm/trunk/src/m/qmu/qmuroot.m
===================================================================
--- /issm/trunk/src/m/qmu/qmuroot.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/qmuroot.m	(revision 13975)
@@ -11,3 +11,2 @@
 	end
 end
-
Index: /issm/trunk/src/m/qmu/rlist_write.m
===================================================================
--- /issm/trunk/src/m/qmu/rlist_write.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/rlist_write.m	(revision 13975)
@@ -68,3 +68,2 @@
 
 end
-
Index: /issm/trunk/src/m/qmu/sensitivities.m
===================================================================
--- /issm/trunk/src/m/qmu/sensitivities.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/sensitivities.m	(revision 13975)
@@ -8,5 +8,4 @@
 %   Example: sens=sensitivities(md,'DragCoefficient','MaxVel');
 %
-
 
 variablenamelength=length(variablename);
Index: /issm/trunk/src/m/qmu/setupdesign/IsScaled.m
===================================================================
--- /issm/trunk/src/m/qmu/setupdesign/IsScaled.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/setupdesign/IsScaled.m	(revision 13975)
@@ -12,5 +12,5 @@
 
 case {'RiftsFriction'},
-	
+
 	status=2; %special treatment
 
Index: /issm/trunk/src/m/qmu/setupdesign/QmuSetupVariables.m
===================================================================
--- /issm/trunk/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/setupdesign/QmuSetupVariables.m	(revision 13975)
@@ -6,5 +6,4 @@
 %decide whether this is a distributed variable, which will drive whether we expand it into npart values,
 %or if we just carry it forward as is. 
-
 
 %ok, key off according to type of descriptor:
Index: /issm/trunk/src/m/qmu/vector_write.m
===================================================================
--- /issm/trunk/src/m/qmu/vector_write.m	(revision 13974)
+++ /issm/trunk/src/m/qmu/vector_write.m	(revision 13975)
@@ -31,5 +31,5 @@
     nitem=nitem+1;
     lsvec=lsvec+1+length(sitem);
-    
+
     if (nitem <= nmax) && (lsvec <= cmax)
         svec=[svec ' ' sitem];
Index: /issm/trunk/src/m/regional/BasinConstrain.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrain.m	(revision 13974)
+++ /issm/trunk/src/m/regional/BasinConstrain.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=BasinConstrain(md,domain);
+function md=BasinConstrain(md,domain)
 %BASINCONSTRAIN - constrain basin
 %
Index: /issm/trunk/src/m/regional/BasinConstrainShelf.m
===================================================================
--- /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 13974)
+++ /issm/trunk/src/m/regional/BasinConstrainShelf.m	(revision 13975)
@@ -1,3 +1,3 @@
-function md=BasinConstrainShelf(md,domain);
+function md=BasinConstrainShelf(md,domain)
 %BASINCONSTRAIN - constrain basin
 %
Index: /issm/trunk/src/m/regional/basinzoom.m
===================================================================
--- /issm/trunk/src/m/regional/basinzoom.m	(revision 13974)
+++ /issm/trunk/src/m/regional/basinzoom.m	(revision 13975)
@@ -39,5 +39,5 @@
 %Ok, find basin we are talking about: 
 load([jplsvn() '/projects/ModelData/Names/Names.mat']);
-		
+
 %Go through names: 
 found=0;
Index: /issm/trunk/src/m/regional/regionaltransient2d.m
===================================================================
--- /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 13974)
+++ /issm/trunk/src/m/regional/regionaltransient2d.m	(revision 13975)
@@ -31,5 +31,5 @@
 
 %take every fields from model
-mde=modelextract(md1,area);
+mde=md1.extract(area);
 mde.private.bamg=[];
 mde.mesh.extractedvertices=nan;
@@ -131,5 +131,5 @@
 	%Diagnostic.  Don't spc the icefront vertices.
 	if ~isnan(md2.diagnostic.icefront)
-		md1s=modelextract(md1,area);
+		md1s=md1.extract(area);
 		%md2.diagnostic.icefront=[md2.mesh.segments 2];
 		e2=md2.mesh.segments(:,end);
@@ -156,3 +156,2 @@
 		md2.results=[];
 	end
-
Index: /issm/trunk/src/m/regional/showbasins.m
===================================================================
--- /issm/trunk/src/m/regional/showbasins.m	(revision 13974)
+++ /issm/trunk/src/m/regional/showbasins.m	(revision 13975)
@@ -21,5 +21,4 @@
 	options=pairoptions(varargin{:});
 end
-
 
 %recover some options, and set defaults
Index: /issm/trunk/src/m/solve/MatlabProcessPatch.m
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.m	(revision 13974)
+++ /issm/trunk/src/m/solve/MatlabProcessPatch.m	(revision 13975)
@@ -1,3 +1,3 @@
-function structure=MatlabProcessPatch(structure);
+function structure=MatlabProcessPatch(structure)
 %PROCESSPATCH - create a structure from a patch
 %
Index: /issm/trunk/src/m/solve/MatlabProcessPatch.py
===================================================================
--- /issm/trunk/src/m/solve/MatlabProcessPatch.py	(revision 13974)
+++ /issm/trunk/src/m/solve/MatlabProcessPatch.py	(revision 13975)
@@ -8,8 +8,8 @@
 
 	#loop over steps
-	for structurei in structure.itervalues():
+	for structurei in structure:
 
 		#return if there is no field Patch
-		if 'Patch' not in structurei:
+		if not hasattr(structurei,'Patch'):
 			continue
 
Index: /issm/trunk/src/m/solve/WriteData.m
===================================================================
--- /issm/trunk/src/m/solve/WriteData.m	(revision 13974)
+++ /issm/trunk/src/m/solve/WriteData.m	(revision 13975)
@@ -231,5 +231,5 @@
 
 	%Get Enum
-	enum=eval([string 'Enum();']); 
+	enum=StringToEnum(string); 
 end % }}}
 function code=FormatToCode(format) % {{{
Index: /issm/trunk/src/m/solve/WriteData.py
===================================================================
--- /issm/trunk/src/m/solve/WriteData.py	(revision 13974)
+++ /issm/trunk/src/m/solve/WriteData.py	(revision 13975)
@@ -17,5 +17,5 @@
 	#process options
 	#  the import above the function level doesn't work?
-	from pairoptions import *
+	from pairoptions import pairoptions
 	options=pairoptions(*args)
 
@@ -101,6 +101,8 @@
 	elif strcmpi(format,'BooleanMat'):    # {{{
 
-		if isinstance(data,bool):
+		if   isinstance(data,bool):
 			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
 		if len(data.shape) == 1:
 			if numpy.size(data):
@@ -132,6 +134,8 @@
 	elif strcmpi(format,'IntMat'):    # {{{
 
-		if isinstance(data,(int,long)):
+		if   isinstance(data,(int,long)):
 			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
 		if len(data.shape) == 1:
 			if numpy.size(data):
@@ -163,6 +167,8 @@
 	elif strcmpi(format,'DoubleMat'):    # {{{
 
-		if isinstance(data,(bool,int,long,float)):
+		if   isinstance(data,(bool,int,long,float)):
 			data=numpy.array([data])
+		elif isinstance(data,(list,tuple)):
+			data=numpy.array(data).reshape(-1,1)
 		if len(data.shape) == 1:
 			if numpy.size(data):
@@ -197,6 +203,8 @@
 		recordlength=4+4    #number of records + code
 		for matrix in data:
-			if isinstance(matrix,(bool,int,long,float)):
+			if   isinstance(matrix,(bool,int,long,float)):
 				matrix=numpy.array([matrix])
+			elif isinstance(matrix,(list,tuple)):
+				matrix=numpy.array(matrix).reshape(-1,1)
 			if len(matrix.shape) == 1:
 				if numpy.size(matrix):
@@ -219,6 +227,8 @@
 		#write each matrix: 
 		for matrix in data:
-			if isinstance(matrix,(bool,int,long,float)):
+			if   isinstance(matrix,(bool,int,long,float)):
 				matrix=numpy.array([matrix])
+			elif isinstance(matrix,(list,tuple)):
+				matrix=numpy.array(matrix).reshape(-1,1)
 			if len(matrix.shape) == 1:
 				matrix=matrix.reshape(numpy.size(matrix),1)
@@ -276,5 +286,5 @@
 
 	#Get Enum
-	exec('enum='+string+'Enum()',globals())
+	enum=StringToEnum(string)[0]
 
 	return enum
Index: /issm/trunk/src/m/solve/loadresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromdisk.m	(revision 13974)
+++ /issm/trunk/src/m/solve/loadresultsfromdisk.m	(revision 13975)
@@ -50,5 +50,4 @@
 	end
 
-
 %post processes qmu results if necessary
 else
Index: /issm/trunk/src/m/solve/loadresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/loadresultsfromdisk.py	(revision 13974)
+++ /issm/trunk/src/m/solve/loadresultsfromdisk.py	(revision 13975)
@@ -1,6 +1,7 @@
 import os
-from collections import OrderedDict
+from results import *
 from parseresultsfromdisk import *
 from EnumToString import EnumToString
+from MatlabFuncs import *
 
 def loadresultsfromdisk(md,filename):
@@ -23,31 +24,35 @@
 
 		#initialize md.results if not a structure yet
-		if not isinstance(md.results,dict):
-			md.results=OrderedDict()
+		if not isinstance(md.results,results):
+			md.results=results()
 
 		#load results onto model
-		structure=parseresultsfromdisk(filename,~md.settings.io_gather)
+		structure=parseresultsfromdisk(filename,not 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;
+		setattr(md.results,structure[0].SolutionType,structure)
 
 		#recover solution_type from results
-		md.private.solution=structure[1]['SolutionType']
+		md.private.solution=structure[0].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]
+				setattr(getattr(md.results,structure[0].SolutionType)[0],'errlog',[line[:-1] for line in f])
 		else:
-			md.results[structure[1]['SolutionType']]['errlog']=[]
+			setattr(getattr(md.results,structure[0].SolutionType)[0],'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]
+				setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[line[:-1] for line in f])
 		else:
-			md.results[structure[1]['SolutionType']]['outlog']=[]
+			setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[])
 
-		if len(md.results[structure[1]['SolutionType']]['errlog']):
+		if len(getattr(md.results,structure[0].SolutionType)[0].errlog):
 			print ("loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields.")
+
+		#if only one solution, extract it from list for user friendliness
+		if len(structure) == 1 and not strcmp(structure[0].SolutionType,'TransientSolution'):
+			setattr(md.results,structure[0].SolutionType,structure[0])
 
 	#post processes qmu results if necessary
Index: /issm/trunk/src/m/solve/marshall.m
===================================================================
--- /issm/trunk/src/m/solve/marshall.m	(revision 13974)
+++ /issm/trunk/src/m/solve/marshall.m	(revision 13975)
@@ -36,9 +36,5 @@
 	%Marshall current object
 	%disp(['marshalling ' field '...']);
-	if verLessThan('matlab', '7.6')
-		marshall(md.(field),fid);
-	else
-		md.(field).marshall(fid);
-	end
+	marshall(md.(field),fid);
 end
 
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.m
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 13974)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.m	(revision 13975)
@@ -19,5 +19,4 @@
 %   Usage:
 %      results=parseresultsfromdiskioserial(filename)
-
 
 %Open file
@@ -54,5 +53,4 @@
 %   Usage:
 %      results=parseresultsfromdiskiosplit(filename)
-
 
 %Open file
@@ -177,5 +175,4 @@
 %      field=ReadDataDimensions(fid)
 
-
 %read field
 [length,count]=fread(fid,1,'int');
Index: /issm/trunk/src/m/solve/parseresultsfromdisk.py
===================================================================
--- /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 13974)
+++ /issm/trunk/src/m/solve/parseresultsfromdisk.py	(revision 13975)
@@ -2,4 +2,5 @@
 import numpy
 from collections import OrderedDict
+import results as resultsclass
 from MatlabFuncs import *
 from MatlabProcessPatch import *
@@ -37,22 +38,22 @@
 		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
 
-	results=OrderedDict()
+	results=[]
 
 	#Read fields until the end of the file.
 	result=ReadData(fid)
 	while result:
+		if result['step'] > len(results):
+			for i in xrange(len(results),result['step']-1):
+				results.append(None)
+			results.append(resultsclass.results())
 		#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'] 
+		setattr(results[result['step']-1],'step',result['step'])
+		setattr(results[result['step']-1],'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']
+		if hasattr(results[result['step']-1],result['fieldname']) and not strcmp(result['fieldname'],'SolutionType'):
+			setattr(results[result['step']-1],result['fieldname'],numpy.vstack((getattr(results[result['step']-1],result['fieldname']),result['field'])))
+		else:
+			setattr(results[result['step']-1],result['fieldname'],result['field'])
 
 		#read next result
@@ -78,5 +79,5 @@
 		raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
 
-	results=OrderedDict()
+	results=[]
 
 	#if we have done split I/O, ie, we have results that are fragmented across patches, 
@@ -86,14 +87,16 @@
 
 		#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'] 
+		if result['step'] > len(results):
+			for i in xrange(len(results),result['step']-1):
+				results.append(None)
+			results.append(resultsclass.results())
+		setattr(results[result['step']-1],'step',result['step'])
+		setattr(results[result['step']-1],'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')
+			setattr(results[result['step']-1],result['fieldname'],[0,result['N']])
+		else:
+			setattr(results[result['step']-1],result['fieldname'],float('NaN'))
 
 		#read next result
@@ -107,6 +110,6 @@
 		#Add result
 		if strcmpi(result['fieldname'],'Patch'):
-			patchdimensions=results[result['step']][result['fieldname']]
-			results[result['step']][result['fieldname']]=[patchdimensions[0]+result['M'],result['N']]
+			patchdimensions=getattr(results[result['step']-1],result['fieldname'])
+			setattr(results[result['step']-1],result['fieldname'],[patchdimensions[0]+result['M'],result['N']])
 
 		#read next result
@@ -116,6 +119,6 @@
 	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
+			setattr(result,'Patch',numpy.zeros((result['Patch'][0],result['Patch'][1])))
+			setattr(result,'counter',0)    #use to index into the patch
 
 	#third pass, this time to read the real information
@@ -125,19 +128,20 @@
 
 		#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'] 
+		if result['step']> len(results):
+			for i in xrange(len(results),result['step']-1):
+				results.append(None)
+			results.append(resultsclass.results())
+		setattr(results[result['step']-1],'step',result['step'])
+		setattr(results[result['step']-1],'time',result['time']) 
 
 		#Add result
 		if strcmpi(result['fieldname'],'Patch'):
-			counter=results[result['step']]['counter']
+			counter=results[result['step']-1].counter
 			counter2=counter+result['field'].shape[0]-1
-			results[result['step']][result['fieldname']][counter:counter2,:]=result['field']
-
+			getattr(results[result['step']-1],result['fieldname'])[counter:counter2,:]=result['field']
 			#increment counter: 
-			results[result['step']]['counter']=counter2+1
-		else:
-			results[result['step']][result['fieldname']]=result['field']
+			results[result['step']-1].counter=counter2+1
+		else:
+			setattr(results[result['step']-1],result['fieldname'],result['field'])
 
 		#read next result
@@ -188,5 +192,5 @@
 
 	except struct.error as e:
-		result=OrderedDict()
+		result=None
 
 	return result
@@ -230,5 +234,5 @@
 
 	except struct.error as e:
-		result=OrderedDict()
+		result=None
 
 	return result
Index: /issm/trunk/src/m/solve/solve.m
===================================================================
--- /issm/trunk/src/m/solve/solve.m	(revision 13974)
+++ /issm/trunk/src/m/solve/solve.m	(revision 13975)
@@ -74,10 +74,8 @@
 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
Index: /issm/trunk/src/m/solve/waitonlock.m
===================================================================
--- /issm/trunk/src/m/solve/waitonlock.m	(revision 13974)
+++ /issm/trunk/src/m/solve/waitonlock.m	(revision 13975)
@@ -12,5 +12,7 @@
 cluster=md.cluster.name;
 login=md.cluster.login;
-port=md.cluster.port;
+if isprop(md.cluster,'port') 
+	port=md.cluster.port;
+end
 timelimit=md.settings.waitonlock;
 filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
Index: /issm/trunk/src/m/solvers/asmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/asmoptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/asmoptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=asmoptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/solvers/iluasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/iluasmoptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=iluasmoptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/solvers/jacobiasmoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/jacobiasmoptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=jacobiasmoptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/solvers/jacobicgoptions.m
===================================================================
--- /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/jacobicgoptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=jacobiasmoptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/solvers/matlaboptions.m
===================================================================
--- /issm/trunk/src/m/solvers/matlaboptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/matlaboptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=matlaboptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/solvers/soroptions.m
===================================================================
--- /issm/trunk/src/m/solvers/soroptions.m	(revision 13974)
+++ /issm/trunk/src/m/solvers/soroptions.m	(revision 13975)
@@ -4,5 +4,5 @@
 %   Usage:
 %      options=soroptions;
-			 
+
 %retrieve options provided in varargin
 options=pairoptions(varargin{:});
Index: /issm/trunk/src/m/string/issmprintf.m
===================================================================
--- /issm/trunk/src/m/string/issmprintf.m	(revision 13974)
+++ /issm/trunk/src/m/string/issmprintf.m	(revision 13975)
@@ -8,5 +8,5 @@
 %   Example:
 %      issmprintf(1,'%s\n','string to display');
-	
+
 if flag,
 	disp(sprintf(format,varargin{:}));
Index: /issm/trunk/src/m/string/strsplit.m
===================================================================
--- /issm/trunk/src/m/string/strsplit.m	(revision 13974)
+++ /issm/trunk/src/m/string/strsplit.m	(revision 13975)
@@ -16,6 +16,4 @@
 
 %   mailto:    gie.spaepen@ua.ac.be
-
-
 
 %Check input arguments
@@ -87,5 +85,4 @@
         splittedstring = tempsplit;
     end
-    
-        
+
 end
Index: /issm/trunk/src/m/string/strsplit_strict.m
===================================================================
--- /issm/trunk/src/m/string/strsplit_strict.m	(revision 13974)
+++ /issm/trunk/src/m/string/strsplit_strict.m	(revision 13975)
@@ -4,5 +4,4 @@
 %   Usage:
 %      output = strsplit_strict(inpstr,delimiter)
-
 
 %Check input arguments
Index: /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp
===================================================================
--- /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/AverageFilter/AverageFilter.cpp	(revision 13975)
@@ -0,0 +1,56 @@
+/*!\file:  AverageFilter.cpp
+ * \brief fill holes in matlab velocity array
+	this matlab module is an adaptation of a routine written by Robber 
+	Crippen.  The original routine was designed for the SRTM mission at JPL, 
+	and can be found in the current directory, under the name 
+	AverageFilterCrippen.  It fills void holes in an image, using an interpolation 
+	algorithm, and optionnally a smoothing algorithm. 
+	This matlab module extends the Crippen routine to be used in Matlab, 
+	using double arrays found in the workspace, and loaded directly into memory.
+*/
+
+#include "./AverageFilter.h"
+
+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;
+
+	/* required input: */
+	double* imagein=NULL;
+	int     imagein_rows,imagein_cols;
+	int     smooth;
+
+
+	/* output: */
+	mxArray* pfield=NULL;
+	double* imageout=NULL;
+	int     imageout_rows,imageout_cols;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&AverageFilterUsage);
+
+	/*Fetch data: */
+	FetchData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
+	FetchData(&smooth,SMOOTH);
+	
+	/*Run core hole filler routine: */
+	AverageFilterx( &imageout,imagein,imagein_rows,imagein_cols,smooth);
+
+	/* output: */
+	WriteData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h
===================================================================
--- /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h	(revision 13975)
+++ /issm/trunk/src/wrappers/AverageFilter/AverageFilter.h	(revision 13975)
@@ -0,0 +1,50 @@
+/*
+	AverageFilter.h
+*/
+
+#ifndef _AVERAGEFILTER_H
+#define _AVERAGEFILTER_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "AverageFilter"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define IMAGEIN prhs[0]
+#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 output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _AVERAGEFILTER_H */
Index: /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.cpp	(revision 13975)
@@ -0,0 +1,61 @@
+/*\file BamgConvertMesh.c
+ *\brief: bamg module.
+ */
+#include "./BamgConvertMesh.h"
+
+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: */
+	int    *index      = NULL;
+	double *x          = NULL;
+	double *y          = NULL;
+	int     nods,nels,test1,test2;
+
+	/*Output*/
+	BamgMesh *bamgmesh = NULL;
+	BamgGeom *bamggeom = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CHECKARGUMENTS(NLHS,NRHS,&BamgConvertMeshUsage);
+
+	/*Initialize Bamg outputs*/
+	bamggeom=new BamgGeom();
+	bamgmesh=new BamgMesh();
+
+	/*Input datasets: */
+	FetchData(&index,&nels,&test1,INDEXHANDLE);
+	FetchData(&x,&nods,XHANDLE);
+	FetchData(&y,&test2,YHANDLE);
+
+	/*Check inputs*/
+	if(nels<0) _error_("Number of elements must be positive, check index number of lines");
+	if(nods<0) _error_("Number of nods must be positive, check x and y sizes");
+	if(test1!=3) _error_("index should have 3 columns");
+	if(test2!=nods) _error_("x and y do not have the same length");
+
+	/* Run core computations: */
+	BamgConvertMeshx(bamgmesh,bamggeom,index,x,y,nods,nels);
+
+	/*Generate output Matlab Structures*/
+	WriteData(BAMGGEOMOUT,bamggeom);
+	WriteData(BAMGMESHOUT,bamgmesh);
+
+	/*Clean up*/
+	delete bamggeom;
+	delete bamgmesh;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h
===================================================================
--- /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgConvertMesh/BamgConvertMesh.h	(revision 13975)
@@ -0,0 +1,55 @@
+/*!\file BamgConvertMesh.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _BAMGCONVERTMESH_H
+#define _BAMGCONVERTMESH_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgConvertMesh"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define INDEXHANDLE prhs[0]
+#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: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  3
+
+#endif
Index: /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgMesher/BamgMesher.cpp	(revision 13975)
@@ -0,0 +1,51 @@
+/*\file BamgMesher.c
+ *\brief: mesher that uses the bamg library
+ */
+#include "./BamgMesher.h"
+
+void BamgMesherUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: [bamgmesh,bamggeom]=" << __FUNCT__ << "(bamgmesh,bamggeom,bamgoptions);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(BamgMesher){
+
+	/*Intermediary*/
+	BamgOpts *bamgopts=NULL;
+	BamgMesh *bamgmesh_in=NULL;
+	BamgGeom *bamggeom_in=NULL;
+	BamgMesh *bamgmesh_out=NULL;
+	BamgGeom *bamggeom_out=NULL;
+
+	/*Boot module*/
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CHECKARGUMENTS(NLHS,NRHS,&BamgMesherUsage);
+
+	/*Initialize outputs*/
+	bamggeom_out=new BamgGeom();
+	bamgmesh_out=new BamgMesh();
+
+	/*Fetch inputs: */
+	FetchData(&bamgopts,BAMGOPTIONS);
+	FetchData(&bamggeom_in,BAMGGEOMIN);
+	FetchData(&bamgmesh_in,BAMGMESHIN);
+
+	/*Call x layer*/
+	Bamgx(bamgmesh_out,bamggeom_out,bamgmesh_in,bamggeom_in,bamgopts);
+
+	/*Generate output Matlab Structures*/
+	WriteData(BAMGGEOMOUT,bamggeom_out);
+	WriteData(BAMGMESHOUT,bamgmesh_out);
+
+	/*Free ressources: */
+	delete bamgopts;
+	delete bamggeom_in;
+	delete bamggeom_out;
+	delete bamgmesh_in;
+	delete bamgmesh_out;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h
===================================================================
--- /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgMesher/BamgMesher.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*
+	BamgMesher.h
+*/
+
+#ifndef _BAMG_MESHER_H_
+#define _BAMG_MESHER_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgMesher"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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 output,0
+#define BAMGGEOMOUT output,1
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _BAMG_MESHER_H_ */
Index: /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp
===================================================================
--- /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.cpp	(revision 13975)
@@ -0,0 +1,56 @@
+/*\file BamgTriangulate.c
+ *\brief: bamg module.
+ */
+#include "./BamgTriangulate.h"
+
+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: */
+	double* x=NULL;
+	double* y=NULL;
+	int     x_cols;
+	int     y_rows,y_cols;
+	int nods;
+
+	/*Output*/
+	int* index=NULL;
+	int  nels;
+
+	/*Intermediary*/
+	int verbose=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&BamgTriangulateUsage);
+
+	/*Input datasets: */
+	if (verbose) _printLine_("Fetching inputs");
+	FetchData(&x,&nods,&x_cols,XHANDLE);
+	FetchData(&y,&y_rows,&y_cols,YHANDLE);
+
+	/*Check inputs*/
+	if(y_rows!=nods)         _error_("x and y do not have the same length");
+	if(x_cols>1 || y_cols>1) _error_("x and y should have only one column");
+	if(nods<3)               _error_("At least 3 points are required");
+
+	/* Run core computations: */
+	if (verbose) _printLine_("Call core");
+	BamgTriangulatex(&index,&nels,x,y,nods);
+
+	/*Write output*/
+	WriteData(INDEX,index,nels,3);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h
===================================================================
--- /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 13975)
+++ /issm/trunk/src/wrappers/BamgTriangulate/BamgTriangulate.h	(revision 13975)
@@ -0,0 +1,52 @@
+/*!\file BamgTriangulate.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _BAMGTRIANGULATE_H
+#define _BAMGTRIANGULATE_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "BamgTriangulate"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define XHANDLE prhs[0]
+#define YHANDLE prhs[1]
+
+/* 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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif
Index: /issm/trunk/src/wrappers/Chaco/Chaco.cpp
===================================================================
--- /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Chaco/Chaco.cpp	(revision 13975)
@@ -0,0 +1,135 @@
+/*\file Chaco.c
+ *\brief:  Chaco partitioner mex module
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Chaco.h"
+
+void ChacoUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("Usage: [assgn] = Chaco(A,vwgts,ewgts,x,y,z,options,nparts,goal);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(Chaco){
+   
+	int i;
+	int nterms;
+
+	/*Inputs: */
+	int     nvtxs;               /* number of vertices in graph           */
+	int    *start;               /* start of edge list for each vertex    */
+	int    *adjacency;           /* edge list data                        */
+	int    *vwgts       = NULL;  /* weights for all vertices              */
+	int     nedges;
+	float  *ewgts       = NULL;  /* weights for all edges                 */
+	float  *x           = NULL;
+	float  *y           = NULL;
+	float  *z           = NULL;  /* coordinates for inertial method       */
+	double  options[10] = {1,1,0,0,1,1,50,0,.001,7654321}; /* architecture and partitioning options */
+	double *in_options  = NULL;
+	int    *nparts      = NULL;   /* number of parts options               */
+	int     npart;
+	double *goal        = NULL;   /* desired set sizes                     */
+
+	/*intermediary pointers: */
+	mwIndex *mwstart, *mwadjacency;
+	double  *doublepointer;
+
+	/*output: */
+   short  *assignment       = NULL; /* set number of each vtx (length nvtxs+1)                */
+   double *doubleassignment = NULL; /*holds assignment, in double format, to return to matlab */
+
+	#ifndef _HAVE_CHACO_ //only works if dakota library has been compiled in.
+	_error_("Chaco not available! Cannot carry out Chaco partitioning!");
+	#endif
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&ChacoUsage);
+
+	/*Fetch adjacency matrix: */
+	nvtxs = mxGetN(A_IN);
+	mwstart = mxGetJc(A_IN);
+	start=xNew<int>((nvtxs+1));
+	for (i=0; i<nvtxs+1;i++)start[i]=(int)mwstart[i];
+
+	mwadjacency = mxGetIr(A_IN);
+	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 = xNewZeroInit<float>(nedges);
+		doublepointer=mxGetPr(A_IN);
+		for (i = 0; i < nedges; i++)ewgts[i] = (float)doublepointer[i];
+	}
+	else ewgts=NULL;
+
+	/*Fetch rest of data: */
+	FetchData(&vwgts,&nterms,VWGTS_IN); 
+	FetchData(&x,&nterms,X_IN); 
+	FetchData(&y,&nterms,Y_IN); 
+	FetchData(&z,&nterms,Z_IN); 
+	FetchData(&in_options,&nterms,OPTNS_IN); 
+	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=xNew<int>(1); nparts[0]=npart; //weird Chacox interface ain't it?
+	FetchData(&goal,&nterms,GOAL_IN); 
+	
+	/*Some debugging print: {{{*/
+	#ifdef _DEBUG_
+	_printLine_("nvtxs: " << nvtxs);
+	_printString_("options: [");
+	for(i=0;i<10;i++)_printString_(options[i] << "|");
+	_printLine_("]");
+	_printLine_("start: ");
+	for (i=0; i<nvtxs+1;i++)_printString_(start[i] << " ");
+	_printLine_("");
+	_printLine_("adjacency: ");
+	for (i=0; i<mxGetNzmax(A_IN);i++)_printString_("" <<adjacency[i]<< " ");i++)
+	_printLine_("");
+	_printLine_("nedges: " << nedges << " " << ewgts);
+	if(ewgts) for (i = 0; i < nedges; i++)_printString_(ewgts[i] << " ");
+	_printLine_("");
+	_printLine_("vwgts:");
+	for (i = 0; i < nvtxs; i++)_printString_(vwgts[i] << " ");
+	_printLine_("");
+	_printLine_("nparts: " << nparts[0]);
+	_printLine_("goal: " << goal);
+	#endif
+	/*}}}*/
+	
+	/*Allocate output: */
+	assignment = xNewZeroInit<short>(nvtxs);
+	
+    /*Call core: */
+	Chacox(nvtxs, start, adjacency, vwgts, ewgts, x, y, z, assignment, options, nparts, goal);
+
+    /*Output data: */
+	doubleassignment=xNew<double>(nvtxs);
+	for(i=0;i<nvtxs;i++) doubleassignment[i]=(double)assignment[i];
+	WriteData(ASSGN_OUT,doubleassignment,nvtxs);
+
+	/*Free ressources:*/
+	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();
+}
Index: /issm/trunk/src/wrappers/Chaco/Chaco.h
===================================================================
--- /issm/trunk/src/wrappers/Chaco/Chaco.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Chaco/Chaco.h	(revision 13975)
@@ -0,0 +1,68 @@
+/*!\file:  Chaco.h
+ * \brief header file for Chaco module.
+ */ 
+
+#ifndef _CHACO_H
+#define _CHACO_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*headers*/
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Chaco"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9
+
+#endif  /* _CHACO_H */
Index: /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.cpp	(revision 13975)
@@ -0,0 +1,89 @@
+/*! \file  ContourtoMesh
+    \brief: takes an  contour file, and figures out which nodes or elements from the mesh  
+    are inside this contour. 
+*/
+	
+#include "./ContourToMesh.h"
+
+void ContourToMeshUsage(void){/*{{{*/
+	_printLine_("CONTOURTOMESH - Flag the elements or nodes inside a contour");
+	_printLine_("");
+	_printLine_("      Usage: ");
+	_printLine_("         [in_nod,in_elem]=ContourToMesh(index,x,y,contourname,interptype,edgevalue)\n");
+	_printLine_("");
+	_printLine_("         index,x,y: mesh triangulation.");
+	_printLine_("         contourname: name of .exp file containing the contours.");
+	_printLine_("         interptype: string definining type of interpolation ('element', or 'node').");
+	_printLine_("         edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.");
+	_printLine_("         in_nod: vector of flags (0 or 1), of size nods if interptype is set to 'node' or 'element and node', ");
+	_printLine_("            or of size 0 otherwise.");
+	_printLine_("         in_elem: vector of flags (0 or 1), of size nel if interptype is set to 'element' or 'element and node', ");
+	_printLine_("            or of size 0 otherwise.");
+	_printLine_("");
+	_printLine_("      Example: ");
+	_printLine_("         in_nod=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','node',1)");
+	_printLine_("         in_elements=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element',0)");
+	_printLine_("         [in_nodes,in_elements]=ContourToMesh(md.elements,md.x,md.y,'Contour.exp','element and node',0)");
+	_printLine_("");
+}/*}}}*/
+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);
+		WriteData(PLHS1);
+	}
+	else if (strcmp(interptype,"element")==0){
+		WriteData(PLHS0,in_elem);
+		WriteData(PLHS1);
+	}
+	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/wrappers/ContourToMesh/ContourToMesh.h
===================================================================
--- /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 13975)
+++ /issm/trunk/src/wrappers/ContourToMesh/ContourToMesh.h	(revision 13975)
@@ -0,0 +1,66 @@
+/*
+	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!"
+#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/toolkits/toolkits.h"
+#include "../../c/include/include.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "ContourToMesh"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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]
+#define PLHS1 (mxArray**)&plhs[1]
+#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 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
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS 6
+
+#endif  /* _CONTOURTOMESH_H */
+
Index: /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp
===================================================================
--- /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.cpp	(revision 13975)
@@ -0,0 +1,49 @@
+/*! \file  ContourtoNodes
+    \brief: takes a  contour file, and figures out which nodes  (x,y list)
+*/
+	
+#include "./ContourToNodes.h"
+
+void ContourToNodesUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [flags]=ContourToNodes(x,y,contourname,edgevalue);\n");
+	_printLine_("   where:");
+	_printLine_("      x,y: list of nodes.");
+	_printLine_("      contourname: name of .exp file containing the contours, or resulting structure from call to expread.");
+	_printLine_("      edgevalue: integer (0, 1 or 2) defining the value associated to the nodes on the edges of the polygons.");
+	_printLine_("      flags: vector of flags (0 or 1), of size nods.");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(ContourToNodes){
+
+	/* input: */
+	int      edgevalue,nods;
+	double  *x           = NULL;
+	double  *y           = NULL;
+	char    *contourname = NULL;
+	DataSet *contours    = NULL;
+
+	/* output: */
+	SeqVec<double> *flags = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CHECKARGUMENTS(NLHS,NRHS,&ContourToNodesUsage);
+	
+	/*Fetch inputs: */
+	FetchData(&x,&nods,NULL,XHANDLE);
+	FetchData(&y,NULL,NULL,YHANDLE);
+	FetchData(&edgevalue,EDGEVALUE);
+	FetchData(&contours,CONTOUR);
+
+	/*Run x layer */
+	ContourToNodesx(&flags,x,y,nods,contours,edgevalue);
+
+	/* output: */
+	WriteData(FLAGS,flags);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h
===================================================================
--- /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 13975)
+++ /issm/trunk/src/wrappers/ContourToNodes/ContourToNodes.h	(revision 13975)
@@ -0,0 +1,57 @@
+/*
+	ContourToNodes.h
+*/
+
+#ifndef _CONTOURTONODES_H
+#define _CONTOURTONODES_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "ContourToNodes"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* input macros: */
+#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: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+#endif  /* _CONTOURTONODES_H */
+
Index: /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.cpp	(revision 13975)
@@ -0,0 +1,41 @@
+/*\file ElementConnectivity.c
+ *\brief: build element connectivity using node connectivity and elements. 
+ */
+
+#include "./ElementConnectivity.h"
+
+void ElementConnectivityUsage(void) {/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: elementconnectivity = " << __FUNCT__ << "(elements, nodeconnectivity);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(ElementConnectivity){
+
+	/*inputs: */
+	double* elements=NULL;
+	double* nodeconnectivity=NULL;
+	int     nel,nods;
+	int     width;
+
+	/*outputs: */
+	double* elementconnectivity=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&ElementConnectivityUsage);
+        
+	/*Input datasets: */
+	FetchData(&elements,&nel,NULL,ELEMENTS);
+	FetchData(&nodeconnectivity,&nods,&width,NODECONNECTIVITY);
+
+	/*!Generate internal degree of freedom numbers: */
+	ElementConnectivityx(&elementconnectivity, elements,nel, nodeconnectivity, nods, width);
+
+	/*write output datasets: */
+	WriteData(ELEMENTCONNECTIVITY,elementconnectivity,nel,3);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 13975)
+++ /issm/trunk/src/wrappers/ElementConnectivity/ElementConnectivity.h	(revision 13975)
@@ -0,0 +1,55 @@
+/*
+	ElementConnectivity.h
+*/
+
+#ifndef _ELEMENTCONNECTIVITY_H
+#define _ELEMENTCONNECTIVITY_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/include/include.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "ElementConnectivity"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define ELEMENTS         prhs[0]
+#define NODECONNECTIVITY prhs[1]
+/* serial output macros: */
+#define ELEMENTCONNECTIVITY (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define ELEMENTS         PyTuple_GetItem(args,0)
+#define NODECONNECTIVITY PyTuple_GetItem(args,1)
+/* serial output macros: */
+#define ELEMENTCONNECTIVITY output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _ELEMENTCONNECTIVITY_H */
Index: /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp
===================================================================
--- /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/EnumToString/EnumToString.cpp	(revision 13975)
@@ -0,0 +1,34 @@
+/*\file EnumToString.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./EnumToString.h"
+
+void EnumToStringUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "string = EnumToString(enum);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(EnumToString){
+
+	char    *name    = NULL;
+	int      enum_in;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&EnumToStringUsage);
+
+	/*Fetch inputs: */
+	FetchData(&enum_in,ENUMIN);
+
+	/*Run core function: */
+	EnumToStringx(&name,enum_in);
+
+	/* output: */
+	WriteData(NAME,name);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/EnumToString/EnumToString.h
===================================================================
--- /issm/trunk/src/wrappers/EnumToString/EnumToString.h	(revision 13975)
+++ /issm/trunk/src/wrappers/EnumToString/EnumToString.h	(revision 13975)
@@ -0,0 +1,49 @@
+/*!\file:  EnumToString.h
+ * \brief header file for EnumToString module.
+ */ 
+
+#ifndef _ENUMTOSTRING_H
+#define _ENUMTOSTRING_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _TEST_H */
Index: /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp
===================================================================
--- /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.cpp	(revision 13975)
@@ -0,0 +1,96 @@
+/*\file Exp2Kml.c
+ *\brief: exp to kml file conversion mex module.
+ */
+#include "./Exp2Kml.h"
+
+void Exp2KmlUsage(void){/*{{{*/
+	_pprintLine_("Exp2Kml - exp to kml file conversion module:");
+	_pprintLine_("");
+	_pprintLine_("   This module converts a file from exp to kml format.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [ret]=Exp2Kml(filexp,filkml,sgn,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      filexp      file name of exp file to be read (char)");
+	_pprintLine_("      filkml      file name of kml file to be written (char)");
+	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
+	_pprintLine_("");
+	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
+	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
+	_pprintLine_("      holes       flag for treatment of multiple profiles (char, optional, 'yes' for holes))");
+	_pprintLine_("");
+	_pprintLine_("      ret         return code (non-zero for warning)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml', 1);");
+	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml', 1,'central_meridian',45,'standard_parallel',70,'holes','yes');");
+	_pprintLine_("      [ret]=Exp2Kml('file.exp','file.kml',-1,'central_meridian', 0,'standard_parallel',71,'holes','yes');");
+	_pprintLine_("");
+}/*}}}*/
+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/wrappers/Exp2Kml/Exp2Kml.h
===================================================================
--- /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Exp2Kml/Exp2Kml.h	(revision 13975)
@@ -0,0 +1,53 @@
+/*!\file Exp2Kml.h
+ * \brief: prototype for exp to kml file conversion mex module.
+ */
+
+#ifndef _EXP2KML_H
+#define _EXP2KML_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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]
+/* 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: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
+
Index: /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp
===================================================================
--- /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/HoleFiller/HoleFiller.cpp	(revision 13975)
@@ -0,0 +1,63 @@
+/*!\file:  HoleFiller.cpp
+ * \brief fill holes in matlab velocity array
+	this matlab module is an adaptation of a routine written by Robber 
+	Crippen.  The original routine was designed for the SRTM mission at JPL, 
+	and can be found in the current directory, under the name 
+	HoleFillerCrippen.  It fills void holes in an image, using an interpolation 
+	algorithm, and optionnally a smoothing algorithm. 
+	This matlab module extends the Crippen routine to be used in Matlab, 
+	using double arrays found in the workspace, and loaded directly into memory.
+*/
+
+#include "./HoleFiller.h"
+
+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;
+
+	/* required input: */
+	double* imagein=NULL;
+	int     imagein_rows,imagein_cols;
+	int     smooth_flag;
+	int     smooth;
+
+
+	/* output: */
+	mxArray* pfield=NULL;
+	double* imageout=NULL;
+	int     imageout_rows,imageout_cols;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&HoleFillerUsage);
+
+	/*Fetch data: */
+	FetchData(&imagein,&imagein_rows,&imagein_cols,IMAGEIN);
+	FetchData(&smooth_flag,SMOOTH);
+	
+	/*Get smooth flag setup: */
+	if (smooth_flag==0)
+		smooth=1;
+	else
+		smooth=0;
+
+	/*Run core hole filler routine: */
+	HoleFillerx( &imageout,imagein,imagein_rows,imagein_cols,smooth);
+
+	/* output: */
+	WriteData(IMAGEOUT,imageout,imagein_rows,imagein_cols);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h
===================================================================
--- /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h	(revision 13975)
+++ /issm/trunk/src/wrappers/HoleFiller/HoleFiller.h	(revision 13975)
@@ -0,0 +1,50 @@
+/*
+	HoleFiller.h
+*/
+
+#ifndef _HOLEFILLER_H
+#define _HOLEFILLER_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "HoleFiller"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define IMAGEIN prhs[0]
+#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 output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _HOLEFILLER_H */
Index: /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp
===================================================================
--- /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InternalFront/InternalFront.cpp	(revision 13975)
@@ -0,0 +1,98 @@
+/*\file InternalFront.c
+ *\brief: build pressureload
+ */
+
+#include "./InternalFront.h"
+
+void InternalFrontUsage(void) {/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: icefront = " << __FUNCT__ << "(md);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InternalFront){
+
+	bool*   elementonwater=NULL;
+	int*    elements=NULL;
+	int*    connectivity=NULL;
+	int*    elementconnectivity=NULL;
+	int*    front=NULL;
+	double* front2=NULL;
+	bool    found;
+	int     numberofelements,numberofsegments;
+	int     N,M;
+	int     i,j,ii,jj,id;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InternalFrontUsage);
+
+	/*Fetch required fields*/
+	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
+	if(numberofelements<=0) _error_("No elements found in the model");
+	FetchData(&elements,&M,&N,mxGetAssignedField(MODEL,0,"elements"));
+	if(M!=numberofelements || N!=3) _error_("Field 'elements' should be of size [md.numberofelements 3]");
+	FetchData(&elementonwater,&M,&N,mxGetAssignedField(MODEL,0,"elementonwater"));
+	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) _error_("Field 'elementconnectivity' should be of size [md.numberofelements 3]");
+
+	/*Allocate and initialize all variables*/
+	numberofsegments=0;
+	front=xNew<int>(3*numberofelements*4);
+
+	/*Loop over all elements on water*/
+	for(i=0;i<numberofelements;i++){
+
+		/*Skip if on water*/
+		if(!elementonwater[i]) continue;
+
+		/*Loop over all three adjacent elements*/
+		for(j=0;j<3;j++){
+
+			/*Skip if adjacent element does not exist or is on water*/
+			id=elementconnectivity[i*3+j];
+			if(id==0) continue;
+			if(elementonwater[id-1]) continue;
+
+			/*We have an ice front to add here, let's go!*/
+			for(ii=0;ii<3;ii++){
+
+				found=false;
+				for(jj=0;jj<3;jj++){
+					if(elements[(id-1)*3+ii]==elements[i*3+jj]){
+						found=true;
+						break;
+					}
+				}
+
+				/*OK, we just found the node of id, which is not in i. We have the segment*/
+				if(!found){
+					front[numberofsegments*4+0]=elements[(id-1)*3+(ii+1)%3];
+					front[numberofsegments*4+1]=elements[(id-1)*3+(ii+2)%3];
+					front[numberofsegments*4+2]=id;
+					front[numberofsegments*4+3]=IceEnum;
+					numberofsegments+=1;
+					break;
+				}
+			}
+
+			/*In debugging mode, check that the segment has been found*/
+			_assert_(!found);
+		}
+	}
+
+	/*Now that we know how many segments there is we can allocate the final matrix*/
+	if(numberofsegments){
+		front2=xNew<double>(4*numberofsegments);
+		for(i=0;i<4*numberofsegments;i++) front2[i]=(double)front[i];
+	}
+	xDelete<int>(front);
+
+	/*write output datasets: */
+	WriteData(FRONT,front2,numberofsegments,4);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InternalFront/InternalFront.h
===================================================================
--- /issm/trunk/src/wrappers/InternalFront/InternalFront.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InternalFront/InternalFront.h	(revision 13975)
@@ -0,0 +1,47 @@
+/*
+	InternalFront.h
+*/
+
+#ifndef _INTERNALFRONT_H
+#define _INTERNALFRONT_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InternalFront"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.cpp	(revision 13975)
@@ -0,0 +1,79 @@
+/*!\file InterpFromGridToMesh.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+	
+#include "./InterpFromGridToMesh.h"
+
+void InterpFromGridToMeshUsage(void){/*{{{*/
+	_pprintLine_("INTERPFROMGRIDTOMESH - interpolation from a grid onto a list of points");
+	_pprintLine_("");
+	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
+	_pprintLine_("   defined on a grid onto a list of points");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      data_mesh=InterpFromGridToMesh(x,y,data,x_mesh,y_mesh,default_value);");
+	_pprintLine_("");
+	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
+	_pprintLine_("      x,y: coordinates of matrix data. (x and y must be in increasing order)");
+	_pprintLine_("      x_mesh,y_mesh: coordinates of the points onto which we interpolate.");
+	_pprintLine_("      default_value: default value if no data is found (holes).");
+	_pprintLine_("      data_mesh: vector of mesh interpolated data.");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      load('velocities.mat');");
+	_pprintLine_("      md.inversion.vx_obs=InterpFromGridToMesh(x_n,y_m,vx,md.mesh.x,md.mesh.y,0);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromGridToMesh){
+
+	int i,j;
+
+	/*input: */
+	double *x = NULL;
+	double *y = NULL;
+	int     x_rows,y_rows;
+	double *data  = NULL;
+	int     data_rows,data_cols;
+	double *x_mesh = NULL;
+	double *y_mesh = NULL;
+	int     x_mesh_rows,y_mesh_rows;
+	double  default_value;
+	int     interpolationenum;
+
+	/* output: */
+	SeqVec<double>*  data_mesh=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	#ifdef _HAVE_MATLAB_MODULES_
+	if((nlhs!=NLHS) || (nrhs!=6 && nrhs!=7)){
+		InterpFromGridToMeshUsage();
+		_error_("usage. See above");
+	}
+	#endif
+
+	/*Input datasets: */
+	FetchData(&x,&x_rows,NULL,XHANDLE);
+	FetchData(&y,&y_rows,NULL,YHANDLE);
+	FetchData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchData(&x_mesh,&x_mesh_rows,NULL,XMESHHANDLE);
+	FetchData(&y_mesh,&y_mesh_rows,NULL,YMESHHANDLE);
+	FetchData(&default_value,DEFAULTHANDLE);
+
+	/* Run core computations: */
+	if(nrhs==7){
+		FetchData(&interpolationenum,INTERPENUM);
+		InterpFromGridToMeshx(&data_mesh, x, x_rows,  y, y_rows, data, data_rows,data_cols, x_mesh, y_mesh, x_mesh_rows,default_value,interpolationenum);
+	}
+	else{
+		InterpFromGridToMeshx(&data_mesh, x, x_rows,  y, y_rows, data, data_rows,data_cols, x_mesh, y_mesh, x_mesh_rows,default_value);
+	}
+
+	/*Write data: */
+	WriteData(DATAMESH,data_mesh);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromGridToMesh/InterpFromGridToMesh.h	(revision 13975)
@@ -0,0 +1,60 @@
+/*!\file InterpFromGridToMesh.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _InterpFromGridToMesh_H
+#define _InterpFromGridToMesh_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromGridToMesh"
+
+#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 DEFAULTHANDLE prhs[5]
+#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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif  /* _INTERPFROMGRIDTOMESH_H */
Index: /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.cpp	(revision 13975)
@@ -0,0 +1,151 @@
+/*!\file InterpFromMesh2d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+	
+#include "./InterpFromMesh2d.h"
+
+void InterpFromMesh2dUsage(void){/*{{{*/
+	_pprintLine_("   usage:");
+	_pprintLine_("         data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime);\n");
+	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value);\n");
+	_pprintLine_("      or data_prime=InterpFromMesh2d(index,x,y,data,x_prime,y_prime,default_value,contourname);\n");
+	_pprintLine_("   where:");
+	_pprintLine_("      x,y: coordinates of the nodes where data is defined");
+	_pprintLine_("      index: index of the mesh where data is defined");
+	_pprintLine_("      data - vector holding the data to be interpolated onto the points.");
+	_pprintLine_("      x_prime,y_prime: coordinates of the mesh vertices onto which we interpolate.");
+	_pprintLine_("      default_value: a scalar or vector of size length(x_prime).");
+	_pprintLine_("      contourname: linear interpolation will happen on all x_interp,y_interp inside the contour, default value will be adopted on the rest of the mesh.");
+	_pprintLine_("      data_prime:  vector of prime interpolated data.");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromMesh2d){
+
+	/*input: */
+	double* index_data=NULL;
+	int     index_data_rows;
+	int     dummy;
+
+	double* x_data=NULL;
+	int     x_data_rows;
+	
+	double* y_data=NULL;
+	int     y_data_rows;
+
+	double* data=NULL; 
+	int     data_rows;
+	int     data_cols;
+
+	double* x_prime=NULL;
+	double* y_prime=NULL;
+	
+	int     x_prime_rows;
+	int     y_prime_rows;
+
+
+	double* default_values=NULL;
+	int     num_default_values=0;
+
+	/*contours*/
+	int i;
+	mxArray *matlabstructure = NULL;
+	Contour<double> **contours=NULL;
+	int numcontours;
+	Contour<double> *contouri=NULL;
+
+	/*Intermediary*/
+	int nods_data;
+	int nels_data;
+	int nods_prime;
+
+	/* output: */
+	SeqVec<double> *data_prime = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs!=NLHS){
+		InterpFromMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+	if((nrhs!=6) && (nrhs!=7) && (nrhs!=8)){
+		InterpFromMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&index_data,&index_data_rows,&dummy,INDEXHANDLE);
+	FetchData(&x_data,&x_data_rows,NULL,XHANDLE);
+	FetchData(&y_data,&y_data_rows,NULL,YHANDLE);
+	FetchData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchData(&x_prime,&x_prime_rows,NULL,XPRIMEHANDLE);
+	FetchData(&y_prime,&y_prime_rows,NULL,YPRIMEHANDLE);
+
+	if(nrhs>=7){
+		/*default values: */
+		FetchData(&default_values,&num_default_values,DEFAULTHANDLE);
+	}
+	else{
+		default_values=NULL;
+		num_default_values=0;
+	}
+
+	if(nrhs>=8){
+		
+		/*Call expread on filename to build a contour array in the matlab workspace: */
+		mexCallMATLAB( 1, &matlabstructure, 1, (mxArray**)&FILENAME, "expread");
+
+		/*contours: */
+		numcontours=mxGetNumberOfElements(matlabstructure);
+		contours=xNew<Contour<double> *>(numcontours);
+		for(i=0;i<numcontours;i++){
+			//allocate
+			contouri=xNew<Contour<double> >(1);
+			//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 vertices " << contouri->nods);
+		  for (j=0;j<contouri->nods;j++){
+		  _printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
+		  }
+		  }*/
+		/*}}}*/
+	}
+	else{
+		numcontours=0;
+		contours=NULL;
+	}
+
+
+	/*some checks*/
+	if (x_data_rows!=y_data_rows){
+		_error_("vectors x and y should have the same length!");
+	}
+	if (x_prime_rows!=y_prime_rows){
+		_error_("vectors x_prime and y_prime should have the same length!");
+	}
+	
+	/*get number of elements and number of nodes in the data*/
+	nels_data=index_data_rows;
+	nods_data=x_data_rows;
+	nods_prime=x_prime_rows;
+
+	/* Run core computations: */
+	InterpFromMesh2dx(&data_prime,index_data,x_data,y_data,nods_data,nels_data,data,data_rows,x_prime,y_prime,nods_prime,default_values,num_default_values,contours,numcontours);
+
+	/*Write data: */
+	WriteData(DATAPRIME,data_prime);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMesh2d/InterpFromMesh2d.h	(revision 13975)
@@ -0,0 +1,60 @@
+/*!\file InterpFromMesh2d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESH2D_H
+#define _INTERPFROMMESH2D_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMesh2d"
+
+#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 DEFAULTHANDLE prhs[6]
+#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: */
+#undef NLHS
+#define NLHS  1
+
+#endif  /* _INTERPFROMMESH2D_H */
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.cpp	(revision 13975)
@@ -0,0 +1,77 @@
+/*\file InterpFromMeshToGrid.c
+ *\brief: compute diff between observed and modeled velocity
+ */
+
+#include "./InterpFromMeshToGrid.h"
+
+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: */
+	double* index=NULL;
+	int     nel;
+	double* x=NULL;
+	int     nods;
+	double* y=NULL;
+	double* meshdata=NULL;
+	int     meshdata_length;
+	double  xmin;
+	double  ymax;
+	double  xposting;
+	double  yposting;
+	int     nlines,ncols;
+	double  default_value;
+
+	/* output datasets: */
+	double* griddata=NULL;
+	double* x_m=NULL;
+	double* y_m=NULL;
+
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToGridUsage);
+
+	/*Input datasets: */
+	FetchData(&index,&nel,NULL,INDEX);
+	FetchData(&x,&nods,NULL,X);
+	FetchData(&y,NULL,NULL,Y);
+	FetchData(&meshdata,&meshdata_length,NULL,MESHDATA);
+	FetchData(&xmin,XMIN);
+	FetchData(&ymax,YMAX);
+	FetchData(&xposting,XPOSTING);
+	FetchData(&yposting,YPOSTING);
+	FetchData(&nlines,NLINES);
+	FetchData(&ncols,NCOLS);
+	FetchData(&default_value,DEFAULTVALUE);
+
+	/*Call core of computation: */
+	InterpFromMeshToGridx(&x_m,&y_m,&griddata,index,x,y,nods,nel,meshdata,meshdata_length,xmin,ymax,xposting,yposting,nlines,ncols,default_value);
+
+	/*Write results: */
+	WriteData(XM,x_m,ncols);
+	WriteData(YM,y_m,nlines);
+	WriteData(GRIDDATA,griddata,nlines,ncols);
+
+	/*Free ressources: */
+	//let matlab do this.
+	
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToGrid/InterpFromMeshToGrid.h	(revision 13975)
@@ -0,0 +1,72 @@
+/*
+	InterpFromMeshToGrid.h
+*/
+
+#ifndef _INTERPFROMMESHTOGRID_H
+#define _INTERPFROMMESHTOGRID_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToGrid"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  3
+#undef NRHS
+#define NRHS  11
+
+#endif  /* _INTERPFROMMESHTOGRID_H*/
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.cpp	(revision 13975)
@@ -0,0 +1,79 @@
+/*\file InterpFromMeshToMesh2d.c
+ *\brief: bamg module.
+ */
+#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){
+
+	/*Intermediaties*/
+	int     *index              = NULL;
+	double  *x_data             = NULL;
+	double  *y_data             = NULL;
+	double  *data               = NULL;
+	int      nods_data,nels_data;
+	int      M_data,N_data;
+	double  *x_interp           = NULL;
+	double  *y_interp           = NULL;
+	int      N_interp;
+	Options *options   = NULL;
+	double  *data_interp = NULL;
+	int      test1,test2,test;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on output arguments on the matlab side: */
+	#ifdef _HAVE_MATLAB_MODULES_
+	if(nlhs!=NLHS){
+		InterpFromMeshToMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+	#endif
+	/*check on input arguments: */
+	if(nrhs<NRHS){
+		InterpFromMeshToMesh2dUsage();
+		_error_("InterpFromMeshToMesh2dUsage usage error");
+	}
+
+	/*Fetch inputs: */
+	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*/
+	InterpFromMeshToMesh2dx(&data_interp,index,x_data,y_data,nods_data,nels_data,data,M_data,N_data,x_interp,y_interp,N_interp,options);
+
+	/*Write data: */
+	WriteData(DATAINTERP,data_interp,N_interp,N_data);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh2d/InterpFromMeshToMesh2d.h	(revision 13975)
@@ -0,0 +1,65 @@
+/*!\file InterpFromMeshToMesh2d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESHTOMESH2d_H
+#define _INTERPFROMMESHTOMESH2d_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/include/include.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToMesh2d"
+
+#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 ARGUMENTS prhs 
+/* serial output macros: */
+#define DATAINTERP (mxArray**)&plhs[0]
+#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 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
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  6
+
+#endif
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.cpp	(revision 13975)
@@ -0,0 +1,101 @@
+/*!\file InterpFromMeshToMesh3d.c
+ * \brief: data interpolation from a list of (x,y,values) into mesh vertices
+*/
+	
+#include "./InterpFromMeshToMesh3d.h"
+
+void InterpFromMeshToMesh3dUsage(void){/*{{{*/
+	_pprintLine_("INTERPFROMMESHTOMESH3D - interpolation from a 3d hexahedron mesh onto a list of point");
+	_pprintLine_("");
+	_pprintLine_("   This function is a multi-threaded mex file that interpolates a field");
+	_pprintLine_("   defined on a triangular mesh onto a list of point");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      data_prime=InterpFromMeshToMesh3d(index,x,y,z,data,x_prime,y_prime,z_prime,default_value);");
+	_pprintLine_("");
+	_pprintLine_("      index: index of the mesh where data is defined");
+	_pprintLine_("      x,y,z: coordinates of the nodes where data is defined");
+	_pprintLine_("      data: matrix holding the data to be interpolated onto the mesh.");
+	_pprintLine_("      x_prime,y_prime,z_prime: coordinates of the points onto which we interpolate.");
+	_pprintLine_("      default_value: default value if no data is found (holes).");
+	_pprintLine_("      data_prime: vector of mesh interpolated data.");
+	_pprintLine_("");
+	_pprintLine_("   Example:");
+	_pprintLine_("      load('temperature.mat');");
+	_pprintLine_("      md.initialization.temperature=InterpFromMeshToMesh3d(index,x,y,z,temperature,md.mesh.x,md.mesh.y,md.mesh.z,253);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(InterpFromMeshToMesh3d){
+
+	/*input: */
+	double* index_data=NULL;
+	int     index_data_rows;
+
+	double* x_data=NULL;
+	double* y_data=NULL;
+	double* z_data=NULL;
+
+	int     x_data_rows;
+	int     y_data_rows;
+	int     z_data_rows;
+
+	double* data=NULL; 
+	int     data_rows;
+	int     data_cols;
+
+	double* x_prime=NULL;
+	double* y_prime=NULL;
+	double* z_prime=NULL;
+	
+	int     x_prime_rows;
+	int     y_prime_rows;
+	int     z_prime_rows;
+
+	double  default_value;
+
+	/*Intermediary*/
+	int nods_data;
+	int nels_data;
+	int nods_prime;
+
+	/* output: */
+	SeqVec<double>*  data_prime=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&InterpFromMeshToMesh3dUsage);
+
+	/*Input datasets: */
+	FetchData(&index_data,&index_data_rows,NULL,INDEXHANDLE);
+	FetchData(&x_data,&x_data_rows,NULL,XHANDLE);
+	FetchData(&y_data,&y_data_rows,NULL,YHANDLE);
+	FetchData(&z_data,&z_data_rows,NULL,ZHANDLE);
+	FetchData(&data,&data_rows,&data_cols,DATAHANDLE);
+	FetchData(&x_prime,&x_prime_rows,NULL,XPRIMEHANDLE);
+	FetchData(&y_prime,&y_prime_rows,NULL,YPRIMEHANDLE);
+	FetchData(&z_prime,&z_prime_rows,NULL,ZPRIMEHANDLE);
+	FetchData(&default_value,DEFAULTHANDLE);
+
+	/*some checks*/
+	if (x_data_rows!=y_data_rows || x_data_rows!=z_data_rows){
+		_error_("vectors x, y and z should have the same length!");
+	}
+	if (x_prime_rows!=y_prime_rows || x_prime_rows!=z_prime_rows){
+		_error_("vectors x_prime, y_prime and z_prime should have the same length!");
+	}
+	/*get number of elements and number of nodes in the data*/
+	nels_data=index_data_rows;
+	nods_data=x_data_rows;
+	nods_prime=x_prime_rows;
+
+	/* Run core computations: */
+	InterpFromMeshToMesh3dx(&data_prime,index_data,x_data,y_data,z_data,nods_data,nels_data,data,data_rows,x_prime,y_prime,z_prime,nods_prime,default_value);
+
+	/*Write data: */
+	WriteData(DATAPRIME,data_prime);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h
===================================================================
--- /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 13975)
+++ /issm/trunk/src/wrappers/InterpFromMeshToMesh3d/InterpFromMeshToMesh3d.h	(revision 13975)
@@ -0,0 +1,64 @@
+/*!\file InterpFromMeshToMesh3d.h
+ * \brief: prototype for Data Interpolation mex module.
+ */
+
+#ifndef _INTERPFROMMESH3D_H
+#define _INTERPFROMMESH3D_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "InterpFromMeshToMesh3d"
+
+#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 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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  9
+
+#endif  /* _INTERPFROMMESHTOMESH3D_H */
Index: /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.cpp	(revision 13975)
@@ -0,0 +1,127 @@
+/*\file KMLFileRead.c
+ *\brief: KML file reader module.
+ */
+#include "./KMLFileRead.h"
+
+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;
+	KML_Object* kobj;
+
+	/*input: */
+	char*   name=NULL;
+	char*   notes=NULL;
+	const mxArray* notesi;
+	mwIndex        nindex;
+	int*    elem=NULL;
+	int     melem=0,nelem=0;
+	int*    nodecon=NULL;
+	int     mncon=0,nncon=0;
+	double* lat=NULL;
+	int     mlat=0,nlat=0,llat=0;
+	double* lng=NULL;
+	int     mlng=0,nlng=0,llng=0;
+	int     nparts=0;
+	int*    part=NULL;
+	int     mprt=0,nprt=0,lprt=0;
+	double* data=NULL;
+	int     mdata=0,ndata=0;
+	double* cmap=NULL;
+	int     mcmap=0,ncmap=0;
+	char*   filnam=NULL;
+	FILE*   fidi=NULL;
+	FILE*   fido=NULL;
+	Options* options=NULL;
+	char*    echo    =NULL;
+	char*    deepecho=NULL;
+	char*    write   =NULL;
+
+	/* output: */
+	int     ierror=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
+	}
+	if (nrhs < NRHS) {
+		KMLFileReadUsage(); _error_("KMLFileRead usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&filnam,FILENAME);
+	FetchData(&options,NRHS,nrhs,prhs);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	options->Get(&echo    ,"echo"    ,(char*)"off");
+	options->Get(&deepecho,"deepecho",(char*)"off");
+	options->Get(&write   ,"write"   ,(char*)"off");
+
+	/*some checks*/
+	if (!strlen(filnam)) strcpy(filnam,"stdout");
+
+	if (verbose) _printLine_("Opening file \"" << filnam << "\".");
+	fidi=fopen(filnam,"r");
+
+	/* Run core computations: */
+	if (verbose) _printLine_("Calling core:");
+	kobj=KMLFileReadx(fidi);
+
+	if (verbose) _printLine_("Closing file \"" << filnam << "\".");
+	fclose(fidi);
+
+	if (kobj){
+		if (!strncmp(echo    ,"on",2) || !strncmp(echo    ,"y",1))
+			kobj->Echo();
+		if (!strncmp(deepecho,"on",2) || !strncmp(deepecho,"y",1))
+			kobj->DeepEcho();
+		if (strncmp(write,"off",3) && strncmp(write,"no",2)) {
+			if (!strncmp(write,"on",2) || !strncmp(write,"yes",3) || !strncmp(write,"stdout",6)) {
+				kobj->Write(stdout,"");
+			}
+			else {
+				if (verbose) _printLine_("Opening file \"" << write << "\".");
+				fido=fopen(write,"w");
+				kobj->Write(fido,"");
+				if (verbose) _printLine_("Closing file \"" << write << "\".");
+				ierror=fclose(fido);
+			}
+		}
+		delete kobj;
+	}
+
+	/*Write data: */
+	WriteData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	xDelete<char>(write);
+	xDelete<char>(deepecho);
+	xDelete<char>(echo);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h
===================================================================
--- /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLFileRead/KMLFileRead.h	(revision 13975)
@@ -0,0 +1,48 @@
+/*!\file KMLFileRead.h
+ * \brief: prototype for KML file reader mex module.
+ */
+
+#ifndef _KMLFILEREAD_H
+#define _KMLFILEREAD_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLFileRead"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.cpp	(revision 13975)
@@ -0,0 +1,148 @@
+/*\file KMLMeshWrite.c
+ *\brief: KML mesh writer module.
+ */
+#include "./KMLMeshWrite.h"
+
+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;
+
+	/*input: */
+	char*   name=NULL;
+	char*   notes=NULL;
+	char*   notes2=NULL;
+	const mxArray* notesi;
+	mwIndex        nindex;
+	int*    elem=NULL;
+	int     melem=0,nelem=0;
+	int*    nodecon=NULL;
+	int     mncon=0,nncon=0;
+	double* lat=NULL;
+	int     mlat=0,nlat=0,llat=0;
+	double* lng=NULL;
+	int     mlng=0,nlng=0,llng=0;
+	int     nparts=0;
+	int*    part=NULL;
+	int     mprt=0,nprt=0,lprt=0;
+	double* data=NULL;
+	int     mdata=0,ndata=0;
+	double* cmap=NULL;
+	int     mcmap=0,ncmap=0;
+	char*   filnam=NULL;
+	FILE*   fid=NULL;
+	Options* options=NULL;
+
+	/* output: */
+	int     ierror=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nlhs > NLHS) {
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
+	}
+	if (nrhs < NRHS) {
+		KMLMeshWriteUsage(); _error_("KMLMeshWrite usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&name,NAME);
+
+/*  notes is typically a cell array of character strings  */
+	if (mxIsCell(NOTES)) {
+		for (nindex=0; nindex<mxGetNumberOfElements(NOTES); nindex++) {
+			notesi=mxGetCell(NOTES,nindex);
+			if (notesi && mxIsChar(notesi) && mxGetNumberOfElements(notesi)) {
+				if (!notes) {
+					notes=xNew<char>(mxGetNumberOfElements(notesi)+1);
+					mxGetString(notesi,notes,mxGetNumberOfElements(notesi)+1);
+				}
+				else {
+/*  note that strlen does not include trailing null  */
+					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);
+				}
+			}
+		}
+	}
+	else
+		FetchData(&notes,NOTES);
+	FetchData(&elem,&melem,&nelem,ELEMHANDLE);
+	FetchData(&nodecon,&mncon,&nncon,NODECONHANDLE);
+	FetchData(&lat,&mlat,&nlat,LATHANDLE);
+	llat=mlat*nlat;
+	FetchData(&lng,&mlng,&nlng,LNGHANDLE);
+	llng=mlng*nlng;
+	FetchData(&part,&mprt,&nprt,PARTHANDLE);
+	lprt=mprt*nprt;
+	FetchData(&data,&mdata,&ndata,DATAHANDLE);
+	FetchData(&cmap,&mcmap,&ncmap,CMAPHANDLE);
+	FetchData(&filnam,FILENAME);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*some checks*/
+	for (i=0; i<melem*nelem; i++) if(elem[i]>nnodes) nnodes=elem[i];
+	if(part) for (i=0; i<lprt; i++) if (part[i]+1 > nparts) nparts=part[i]+1;
+
+	if (nodecon && (mncon != nnodes))
+	  {_error_("Nodal connectivity table, if supplied, must be supplied for all nodes.");}
+	else if (!nodecon)
+		mncon=nnodes;
+	if ((llat != nnodes) || (llng != nnodes) || (llat != llng))
+		_error_("Latitude and longitude vectors must be supplied for all nodes.");
+	if (part && (lprt != nnodes))
+		_error_("Partitioning vector, if supplied, must be supplied for all nodes.");
+	if (data && !((mdata == nnodes) || (mdata == melem)))
+		_error_("Data matrix, if supplied, must be supplied for all nodes or all elements.");
+	if (cmap && (ncmap != 3))
+		_error_("Colormap matrix, if supplied, must have three columns for rgb.");
+	if (!strlen(filnam))
+		strcpy(filnam,"stdout");
+
+	/* Run core computations: */
+	fid=fopen(filnam,"w");
+	KMLMeshWritex(&ierror,name,notes,elem,melem,nelem,nodecon,mncon,nncon,lat,lng,part,data,mdata,ndata,cmap,mcmap,ncmap,fid);
+	fclose(fid);
+
+	/*Write data: */
+	WriteData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	delete options;
+	if (mxIsCell(NOTES) && notes) xDelete<char>(notes);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h
===================================================================
--- /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLMeshWrite/KMLMeshWrite.h	(revision 13975)
@@ -0,0 +1,66 @@
+/*!\file KMLMeshWrite.h
+ * \brief: prototype for KML mesh writer mex module.
+ */
+
+#ifndef _KMLMESHWRITE_H
+#define _KMLMESHWRITE_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLMeshWrite"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define NAME          prhs[0]
+#define NOTES         prhs[1]
+#define ELEMHANDLE    prhs[2]
+#define NODECONHANDLE prhs[3]
+#define LATHANDLE     prhs[4]
+#define LNGHANDLE     prhs[5]
+#define PARTHANDLE    prhs[6]
+#define DATAHANDLE    prhs[7]
+#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: */
+#undef NRHS
+#define NRHS 10
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp
===================================================================
--- /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.cpp	(revision 13975)
@@ -0,0 +1,133 @@
+/*\file KMLOverlay.c
+ *\brief: KML file overlay mex module.
+ */
+#include "./KMLOverlay.h"
+
+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;
+
+	/*input: */
+	char*   filkml=NULL;
+	char*   filkmz=NULL;
+
+	FILE*   fid=NULL;
+
+	Options* options=NULL;
+	int      nlat=0,nlong=0;
+	double*  lataxis =NULL;
+	double*  longaxis=NULL;
+	int      nimages=0;
+	char**   pimages=NULL;
+	double   dzip=0;
+	char*    czip=NULL;
+
+	/* output: */
+	int     ierror=0;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if(nlhs>NLHS){
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
+	}
+	if(nrhs<NRHS){
+		KMLOverlayUsage(); _error_("KMLOverlay usage error");
+	}
+
+	/*Input datasets: */
+	FetchData(&filkml,FILENAME);
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	options->Get(&lataxis ,&nlat ,(char*)"lataxis");
+	if (verbose && lataxis) for (i=0; i<nlat; i++) _printLine_("  lataxis [" << i << "]=" << lataxis[i]);
+	options->Get(&longaxis,&nlong,(char*)"longaxis");
+	if (verbose && longaxis) for (i=0; i<nlong; i++) _printLine_("  longaxis[" << i << "]=" << longaxis[i]);
+	options->Get(&pimages,&nimages,(char*)"images");
+	if (verbose && pimages) for (i=0; i<nimages; i++) _printLine_("  pimages[" << i << "]=\"" << pimages[i] << "\"");
+	options->Get(&dzip,(char*)"zip",0.);
+	if (verbose) _printLine_("  dzip=" << dzip);
+
+	/*some checks*/
+	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){
+		filkmz=filkml;
+		filkml=(char*)mxMalloc(8*sizeof(char));
+		strcpy(filkml,"doc.kml");
+	}
+
+	if(!strlen(filkml)) strcpy(filkml,"stdout");
+
+	if(verbose) _printLine_("Opening kml overlay file \"" << filkml << "\".");
+	fid=fopen(filkml,"w");
+
+	/* Run core computations: */
+	if (verbose) _printLine_("Calling core:");
+	KMLOverlayx(&ierror,lataxis,longaxis,nimages,pimages,fid);
+
+	if (verbose) _printLine_("Closing file \"" << filkml << "\".");
+	fclose(fid);
+
+	/* Create kmz file, if specified: */
+	if ((int)dzip) {
+		czip=(char*)mxMalloc((5+strlen(filkmz)+1+strlen(filkml)+1)*sizeof(char));
+		czip[0]='\0';
+		strcat(czip,"!zip ");
+		strcat(czip,filkmz);
+		strcat(czip," ");
+		strcat(czip,filkml);
+		for (i=0; i<nimages; i++)
+			if (strlen(pimages[i]) && strncmp(pimages[i],"http",4)) {
+				czip=(char*)mxRealloc(czip,(strlen(czip)+1+strlen(pimages[i])+1)*sizeof(char));
+				strcat(czip," ");
+				strcat(czip,pimages[i]);
+			}
+		if (verbose) _printLine_("Zipping file \"" << filkmz << "\".");
+		if (verbose) _printLine_(czip);
+
+		if (mexEvalString(czip)) _error_("Error zipping file \"" << filkmz << "\".");
+		xDelete<char>(czip);
+		xDelete<char>(filkmz);
+	}
+
+	/*Write data: */
+	WriteData(ERRORFLAG,ierror);
+
+	/*Clean-up*/
+	if (pimages) {
+		for (i=nimages; i>0; i--) xDelete<char>(pimages[i-1]);
+		xDelete<char*>(pimages);
+	}
+	xDelete<double>(longaxis);
+	xDelete<double>(lataxis);
+	xDelete<char>(filkml);
+	delete options;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h
===================================================================
--- /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 13975)
+++ /issm/trunk/src/wrappers/KMLOverlay/KMLOverlay.h	(revision 13975)
@@ -0,0 +1,48 @@
+/*!\file KMLOverlay.h
+ * \brief: prototype for KML file overlay mex module.
+ */
+
+#ifndef _KMLOVERLAY_H
+#define _KMLOVERLAY_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "KMLOverlay"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NRHS
+#define NRHS  1
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp
===================================================================
--- /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.cpp	(revision 13975)
@@ -0,0 +1,88 @@
+/*\file Kml2Exp.c
+ *\brief: kml to exp file conversion mex module.
+ */
+#include "./Kml2Exp.h"
+
+void Kml2ExpUsage(void){/*{{{*/
+	_pprintLine_("Kml2Exp - kml to exp file conversion module:");
+	_pprintLine_("");
+	_pprintLine_("   This module converts a file from kml to exp format.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [ret]=Kml2Exp(filexp,filkml,sgn,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      filkml      file name of kml file to be read (char)");
+	_pprintLine_("      filexp      file name of exp file to be written (char)");
+	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
+	_pprintLine_("");
+	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
+	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
+	_pprintLine_("");
+	_pprintLine_("      ret         return code (non-zero for warning)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp', 1);");
+	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp', 1,'central_meridian',45,'standard_parallel',70);");
+	_pprintLine_("      [ret]=Kml2Exp('file.kml','file.exp',-1,'central_meridian', 0,'standard_parallel',71);");
+	_pprintLine_("");
+}/*}}}*/
+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/wrappers/Kml2Exp/Kml2Exp.h
===================================================================
--- /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Kml2Exp/Kml2Exp.h	(revision 13975)
@@ -0,0 +1,52 @@
+/*!\file Kml2Exp.h
+ * \brief: prototype for kml to exp file conversion mex module.
+ */
+
+#ifndef _KML2EXP_H
+#define _KML2EXP_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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]
+/* 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: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
Index: /issm/trunk/src/wrappers/Kriging/Kriging.cpp
===================================================================
--- /issm/trunk/src/wrappers/Kriging/Kriging.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Kriging/Kriging.cpp	(revision 13975)
@@ -0,0 +1,73 @@
+/*\file Kriging.c
+ *\brief: best linear predictor
+ */
+#include "./Kriging.h"
+
+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*/
+	double  *x            = NULL;
+	double  *y            = NULL;
+	double  *observations = NULL;
+	double  *x_interp     = NULL;
+	double  *y_interp     = NULL;
+	double  *predictions  = NULL;
+	double  *error        = NULL;
+	Options *options      = NULL;
+	int      N_interp,M_interp,M,N,n_obs;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	if (nrhs<NRHS || nlhs>NLHS){
+		KrigingUsage(); _error_("Kriging usage error");
+	}
+
+	/*Fetch inputs: */
+	FetchData(&x,&n_obs,X);
+	FetchData(&y,&N,Y);                       if(n_obs!=N) _error_("x and y should have the same size");
+	FetchData(&observations,&N,OBSERVATIONS); if(n_obs!=N) _error_("x and observations should have the same size");
+	FetchData(&x_interp,&M_interp,&N_interp,XINTERP);
+	FetchData(&y_interp,&M,&N,YINTERP);       if(N!=N_interp || M!=M_interp) _error_("x_interp and y_interp should have the same size");
+	FetchData(&options,NRHS,nrhs,prhs);
+
+	/*Call x layer*/
+	Krigingx(&predictions,&error,x,y,observations,n_obs,x_interp,y_interp,M_interp*N_interp,options);
+
+	/*Generate output Matlab Structures*/
+	if(nlhs>=1) WriteData(PREDICTIONS,predictions,M_interp,N_interp);
+	if(nlhs==2) WriteData(ERROR,error,M_interp,N_interp);
+
+	/*Free ressources: */
+	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();
+}
Index: /issm/trunk/src/wrappers/Kriging/Kriging.h
===================================================================
--- /issm/trunk/src/wrappers/Kriging/Kriging.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Kriging/Kriging.h	(revision 13975)
@@ -0,0 +1,59 @@
+/*
+	Kriging.h
+*/
+
+#ifndef _KRIGING_H_
+#define _KRIGING_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "Kriging"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  5
+
+#endif  /* _KRIGING_H_ */
Index: /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp
===================================================================
--- /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Ll2xy/Ll2xy.cpp	(revision 13975)
@@ -0,0 +1,97 @@
+/*\file Ll2xy.c
+ *\brief: lat/long to x/y coordinate mex module.
+ */
+#include "./Ll2xy.h"
+
+void Ll2xyUsage(void){/*{{{*/
+	_pprintLine_("Ll2xy - lat/long to x/y coordinate transformation module:");
+	_pprintLine_("");
+	_pprintLine_("   This module transforms lat/long to x/y coordinates.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [x,y]=Ll2xy(lat,lon,sgn,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      lat         latitude coordinates (double vector)");
+	_pprintLine_("      lon         longitude coordinates (double vector)");
+	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
+	_pprintLine_("");
+	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
+	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
+	_pprintLine_("");
+	_pprintLine_("      x           x coordinates (double vector)");
+	_pprintLine_("      y           y coordinates (double vector)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [x,y]=Ll2xy(lat,lon, 1);");
+	_pprintLine_("      [x,y]=Ll2xy(lat,lon, 1,'central_meridian',45,'standard_parallel',70);");
+	_pprintLine_("      [x,y]=Ll2xy(lat,lon,-1,'central_meridian', 0,'standard_parallel',71);");
+	_pprintLine_("");
+}/*}}}*/
+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/wrappers/Ll2xy/Ll2xy.h
===================================================================
--- /issm/trunk/src/wrappers/Ll2xy/Ll2xy.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Ll2xy/Ll2xy.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*!\file Ll2xy.h
+ * \brief: prototype for lat/long to x/y coordinate mex module.
+ */
+
+#ifndef _LL2XY_H
+#define _LL2XY_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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 PyTuple_GetItem(args,0)
+#define LON_IN PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define X_OUT output,0
+#define Y_OUT output,1
+#endif
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  2
+
+#endif
Index: /issm/trunk/src/wrappers/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/Makefile.am	(revision 13975)
+++ /issm/trunk/src/wrappers/Makefile.am	(revision 13975)
@@ -0,0 +1,8 @@
+SUBDIRS = 
+if MATLAB
+SUBDIRS += matlab
+endif
+
+if PYTHON
+SUBDIRS += python
+endif
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.cpp	(revision 13975)
@@ -0,0 +1,84 @@
+/*!\file:  MeshPartition.cpp
+ * \brief: partition mesh according to number of areas, using Metis library.
+*/
+	
+#include "./MeshPartition.h"
+
+void MeshPartitionUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printString_("   [element_partitioning,node_partitioning]=MeshPartition(md.mesh,numpartitions)");
+	_printLine_("   where:");
+	_printLine_("      element_partitioning is a vector of partitioning area numbers, for every element.");
+	_printLine_("      node_partitioning is a vector of partitioning area numbers, for every node.");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(MeshPartition){
+
+	/*Indexing: */
+	int i,j;
+
+	/* required input: */
+	int     dim;
+	int     numberofelements;
+	int     numberofvertices;
+	double *elements         = NULL;
+	int     elements_width;
+
+	int numberofelements2d;
+	int numberofvertices2d;
+	double* elements2d=NULL;
+
+	int numberoflayers;
+	int numareas=1;
+
+	/* output: */
+	int    *int_element_partitioning = NULL;
+	int    *int_node_partitioning    = NULL;
+	double *element_partitioning     = NULL;
+	double *node_partitioning        = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&MeshPartitionUsage);
+
+	/*Fetch data: */
+	FetchData(&dim,mxGetAssignedField(MODEL,0,"dimension"));
+	FetchData(&numberofelements,mxGetAssignedField(MODEL,0,"numberofelements"));
+	FetchData(&numberofvertices,mxGetAssignedField(MODEL,0,"numberofvertices"));
+	FetchData(&elements,NULL,&elements_width,mxGetAssignedField(MODEL,0,"elements"));
+
+	if (dim==3){
+		FetchData(&numberofelements2d,mxGetAssignedField(MODEL,0,"numberofelements2d"));
+		FetchData(&numberofvertices2d,mxGetAssignedField(MODEL,0,"numberofvertices2d"));
+		FetchData(&elements2d,NULL,NULL,mxGetAssignedField(MODEL,0,"elements2d"));
+	}
+	FetchData(&numberoflayers,mxGetAssignedField(MODEL,0,"numberoflayers"));
+	FetchData(&numareas,NUMAREAS);
+
+	/*Run partitioning algorithm based on a "clever" use of the Metis partitioner: */
+	MeshPartitionx(&int_element_partitioning,&int_node_partitioning,numberofelements,numberofvertices,elements,
+		numberofelements2d,numberofvertices2d,elements2d,numberoflayers,elements_width,dim,numareas);
+
+	/*Post process node_partitioning and element_partitioning to be in double format. Metis needed them in int* format: */
+	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=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.
+	}
+
+	/*Write data:*/
+	WriteData(ELEMENTPARTITIONING,element_partitioning,numberofelements);
+	WriteData(NODEPARTITIONING,node_partitioning,numberofvertices);
+	
+	/*Free ressources:*/
+	//don't! let matlab do it.
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h
===================================================================
--- /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 13975)
+++ /issm/trunk/src/wrappers/MeshPartition/MeshPartition.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*
+	MeshPartition.h
+*/
+
+#ifndef _MESHPARTITION_H
+#define _MESHPARTITION_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "MeshPartition"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  2
+#undef NRHS
+#define NRHS  2
+
+
+#endif  /* _MESHPARTITION_H */
+
Index: /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp
===================================================================
--- /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.cpp	(revision 13975)
@@ -0,0 +1,104 @@
+/*! \file  MeshProfileIntersection.cpp
+    \brief: takes a  .exp file (made of several profiles), and figures out its intersection 
+	with a mesh.
+
+	usage:
+	[segments]=MeshProfileIntersection(index,x,y,filename);
+
+	where:
+	input:
+		index,x,y is a triangulation
+		filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)
+	output:
+		segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremities for a segment 
+		belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the 
+		mesh.
+*/
+	
+#include "./MeshProfileIntersection.h"
+
+void MeshProfileIntersectionUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [segments]=MeshProfileIntersection(index,x,y,filename);");
+	_printLine_("   where:");
+	_printLine_("   input:");
+	_printLine_("        index,x,y is a triangulation");
+	_printLine_("        filename: name of Argus style .exp file containing the segments (can be groups of disconnected segments)");
+	_printLine_("   output:");
+	_printLine_("        segments: array made of x1,y1,x2,y2,element_id lines (x1,y1) and (x2,y2) are segment extremities for a segment ");
+	_printLine_("        belonging to the elemnt_id element. there are as many lines in segments as there are segments intersecting the ");
+	_printLine_("        mesh.");
+}/*}}}*/
+WRAPPER(MeshProfileIntersection){
+
+	int i,j;
+
+	/* required input: */
+	//mesh
+	double* double_index=NULL;
+	int*    index=NULL;
+	int     nel;
+	double* x=NULL;
+	double* y=NULL;
+	int     nods;
+	int     dummy;
+	
+	//contours
+	DataSet *domain = NULL;
+	Contour<double>** contours=NULL;
+	int       numcontours;
+	Contour<double>*  contouri=NULL;
+
+	/* output: */
+	double* segments=NULL;
+	int     numsegs;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&MeshProfileIntersectionUsage);
+
+	/*Fetch inputs: */
+	//index
+	FetchData(&double_index,&nel,&dummy,INDEX);
+	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++){
+			*(index+3*i+j)=(int)*(double_index+dummy*i+j)-1; //"C" style indexing
+		}
+	}
+	//x and y
+	FetchData(&x,&nods,X);
+	FetchData(&y,&dummy,Y);
+
+	//contours
+	FetchData(&domain,FILENAME);
+	// MeshProfileIntersectionx should be modified to take DataSet directly (and perhaps SeqMat and SeqVec).
+	numcontours=domain->Size();
+	contours=xNew<Contour<double>*>(numcontours);
+	for(i=0;i<numcontours;i++)
+		*(contours+i)=(Contour<double>*)domain->GetObjectByOffset(i);
+
+	/* Debugging of contours :{{{1*/
+	/*for(i=0;i<numcontours;i++){
+		_printLine_("\nContour echo: contour number  " << i+1 << " / " << numcontours);
+		contouri=*(contours+i);
+		_printLine_("   Number of vertices " << contouri->nods);
+		for (j=0;j<contouri->nods;j++){
+			_printLine_("   " << *(contouri->x+j) << "f " << *(contouri->y+j) << "f");
+		}
+	}*/
+	/*}}}*/
+
+	/*Run interpolation routine: */
+	MeshProfileIntersectionx(&segments,&numsegs,index,x,y,nel,nods,contours,numcontours);
+
+	/* output: */
+	WriteData(SEGMENTS,segments,numsegs,5);
+
+	/*end module: */
+	MODULEEND();
+
+}
Index: /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h
===================================================================
--- /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 13975)
+++ /issm/trunk/src/wrappers/MeshProfileIntersection/MeshProfileIntersection.h	(revision 13975)
@@ -0,0 +1,55 @@
+/*
+	MeshProfileIntersection.h
+*/
+
+#ifndef _MESHPROFILEINTERSECTION_H
+#define _MESHPROFILEINTERSECTION_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "MeshProfileIntersection"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* input macros: */
+#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: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+#endif  /* _MESHPROFILEINTERSECTION_H */
+
Index: /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.cpp	(revision 13975)
@@ -0,0 +1,41 @@
+/*\file NodeConnectivity.c
+ *\brief: build node connectivity from elements. 
+ */
+
+#include "./NodeConnectivity.h"
+
+void NodeConnectivityUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: connectivity = " << __FUNCT__ << "(elements, numnodes);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(NodeConnectivity){
+
+	/*inputs: */
+	double* elements=NULL;
+	int     nel;
+	int     nods;
+
+	/*outputs: */
+	double* connectivity=NULL;
+	int     width;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&NodeConnectivityUsage);
+        
+	/*Input datasets: */
+	FetchData(&elements,&nel,NULL,ELEMENTS);
+	FetchData(&nods,NUMNODES);
+
+	/*!Generate internal degree of freedom numbers: */
+	NodeConnectivityx(&connectivity, &width,elements,nel, nods);
+
+	/*write output datasets: */
+	WriteData(CONNECTIVITY,connectivity,nods,width);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 13975)
+++ /issm/trunk/src/wrappers/NodeConnectivity/NodeConnectivity.h	(revision 13975)
@@ -0,0 +1,55 @@
+/*
+	NodeConnectivity.h
+*/
+
+#ifndef _NODECONNECTIVITY_H
+#define _NODECONNECTIVITY_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#undef __FUNCT__ 
+#define __FUNCT__  "NodeConnectivity"
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/include/include.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define ELEMENTS prhs[0]
+#define NUMNODES prhs[1]
+/* serial output macros: */
+#define CONNECTIVITY (mxArray**)&plhs[0]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define ELEMENTS PyTuple_GetItem(args,0)
+#define NUMNODES PyTuple_GetItem(args,1)
+/* serial output macros: */
+#define CONNECTIVITY output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  2
+
+#endif  /* _NODECONNECTIVITY_H */
Index: /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp
===================================================================
--- /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.cpp	(revision 13975)
@@ -0,0 +1,51 @@
+/*! \file  PointCloudFindNeighbors
+    \brief: flag points that are too near one another, within an array of point coordinates
+*/
+	
+#include "./PointCloudFindNeighbors.h"
+
+void PointCloudFindNeighborsUsage(void){/*{{{*/
+	_printLine_("   usage:");
+	_printLine_("   [flags]=PointCloudFindNeighbors(x,y,mindistance,multithread);\n");
+	_printLine_("   where:");
+	_printLine_("      x,y: list of points.");
+	_printLine_("      mindistance: minimum distance that should exist between points in the cloud.");
+	_printLine_("      multithread: run multithreaded or not. with multithreads, flags can get 1 and 2 values in duplicates.");
+	_printLine_("      flags: array of flags (flag==1 means point is within mindistance of another point)");
+	_printLine_("");
+}/*}}}*/
+WRAPPER(PointCloudFindNeighbors){
+
+	int i,j;
+
+	/* required input: */
+	double *x = NULL;
+	double *y = NULL;
+	int     nods;
+	double  mindistance;
+	double  multithread;
+
+	/* output: */
+	SeqVec<double> *flags = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&PointCloudFindNeighborsUsage);
+
+	/*Fetch inputs: */
+	FetchData(&x,&nods,NULL,XHANDLE);  
+	FetchData(&y,NULL,NULL,YHANDLE);
+	FetchData(&mindistance,MINDISTANCE);
+	FetchData(&multithread,MULTITHREAD);
+
+	/*Run core routine: */
+	PointCloudFindNeighborsx(&flags,x,y,nods,mindistance,multithread);
+
+	/* output: */
+	WriteData(FLAGS,flags);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h
===================================================================
--- /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 13975)
+++ /issm/trunk/src/wrappers/PointCloudFindNeighbors/PointCloudFindNeighbors.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*
+	PointCloudFindNeighbors.h
+*/
+
+#ifndef _POINTCLOUDFINDNEIGHBORS_H
+#define _POINTCLOUDFINDNEIGHBORS_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__
+#define __FUNCT__ "PointCloudFindNeighbors"
+
+#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     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 output,0
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS 1
+#undef NRHS
+#define NRHS 4
+
+#endif  /* _POINTCLOUDFINDNEIGHBORS_H */
Index: /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp
===================================================================
--- /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.cpp	(revision 13975)
@@ -0,0 +1,46 @@
+/*\file PropagateFlagsFromConnectivity.c
+ *\brief: propagate flags onto mesh, element by element, using connectivity.
+ */
+
+#include "./PropagateFlagsFromConnectivity.h"
+
+void PropagateFlagsFromConnectivityUsage(void) {/*{{{*/
+	_printLine_("");
+	_printLine_("   usage: [pool] = " << __FUNCT__ << "(connectivity,pool,index,flags);");;
+	_printLine_("");
+}/*}}}*/
+WRAPPER(PropagateFlagsFromConnectivity){
+
+	/*input/output datasets: */
+	double* connectivity=NULL;
+	int     nel;
+	double* pool=NULL;
+	double* flags=NULL;
+	int     index;
+	int     dummy;
+	
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&PropagateFlagsFromConnectivityUsage);
+        
+	/*Input datasets: */
+	FetchData(&connectivity,&nel,&dummy,CONNECTIVITY);
+	FetchData(&pool,&dummy,POOL);
+	FetchData(&index,INDEX);
+	FetchData(&flags,&dummy,FLAGS);
+
+	/*!Generate internal degree of freedom numbers: */
+	PropagateFlagsFromConnectivityx(pool,connectivity,index,flags);
+
+	/*write output datasets: */
+	WriteData(POOLOUT,pool,nel);
+
+	/*Free ressources: */
+	xDelete<double>(connectivity);
+	xDelete<double>(flags);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h
===================================================================
--- /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 13975)
+++ /issm/trunk/src/wrappers/PropagateFlagsFromConnectivity/PropagateFlagsFromConnectivity.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*
+	PropagateFlagsFromConnectivity.h
+*/
+
+#ifndef _PROPAGATEFLAGSFROMCONNECTIVITY_H
+#define _PROPAGATEFLAGSFROMCONNECTIVITY_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "PropagateFlagsFromConnectivity"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  4
+
+#endif  /* _PROPAGATEFLAGSFROMCONNECTIVITY_H */
Index: /issm/trunk/src/wrappers/Scotch/Scotch.cpp
===================================================================
--- /issm/trunk/src/wrappers/Scotch/Scotch.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Scotch/Scotch.cpp	(revision 13975)
@@ -0,0 +1,249 @@
+/*\file Scotch.c
+ *\brief:  Scotch partitioner mex module
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include "./Scotch.h"
+
+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
+
+	int     argcm;
+	char    **argvm=NULL;
+	int     nvert =0,nedge2=0,napar =0;
+	mwIndex *ir=NULL,*jc=NULL;
+	int     *adjir=NULL,*adjjc=NULL;
+	double  *vld=NULL,*vwd=NULL,*ewd=NULL,*apd=NULL;
+	int     *vli=NULL,*vwi=NULL,*ewi=NULL,*api=NULL;
+	char    *archtyp=NULL;
+	int     (*maptabi)[2]=NULL;
+	double* maptabd=NULL;
+	int     i,j,k,imi=0,imo=0,isi=0,ierr;
+
+	/* Check for proper number of arguments */
+   
+	if (nrhs == 0 && nlhs == 0) {
+		GmapUsage();
+		return;
+	}
+	else if (nrhs <  6 || nlhs >  1) {
+		GmapUsage();
+		mexErrMsgTxt(" ");
+	}
+
+/*  load matlab argument list and convert to integer (note that converting here
+	and in the x-layer is inefficient, but it makes the x-layer more general)  */
+
+	argvm = (char **) calloc(nrhs,sizeof(char *));
+
+	if (!(mxIsNumeric(prhs[imi]) &&
+		  (mxGetM(prhs[imi]) == 1 && mxGetN(prhs[imi]) == 1))) {
+		argvm[isi] = (char *) calloc(4+1,sizeof(char));
+		strcpy(argvm[isi],"gmap");
+		mexPrintf("%s -- Using \"%s\" entry point.\n",
+				  __FUNCT__,argvm[isi]);
+		isi++;
+	}
+	else {
+		argvm[isi] = (char *) calloc(5+1,sizeof(char));
+		strcpy(argvm[isi],"gpart");
+		mexPrintf("%s -- Using \"%s\" entry point.\n",
+				  __FUNCT__,argvm[isi]);
+		isi++;
+
+		argvm[isi] = (char *) calloc(17,sizeof(char));
+		sprintf(argvm[isi],"%d",(int)mxGetScalar(prhs[imi]));
+		mexPrintf("%s -- Number of parts is %s.\n",
+				  __FUNCT__,argvm[isi]);
+		isi++;
+		imi++;
+	}
+
+	if (!mxIsNumeric(prhs[imi]) || (!mxIsEmpty(prhs[imi]) && !mxIsSparse(prhs[imi]))) {
+		mexPrintf("%s -- Adjacency matrix must be numeric and sparse.\n",__FUNCT__);
+		mexErrMsgTxt(" ");
+	}
+	else {
+		nvert =mxGetM(prhs[imi]);
+		nedge2=mxGetNzmax(prhs[imi]);
+		if (mxGetNzmax(prhs[imi])) {
+			ir    =mxGetIr(prhs[imi]);
+			adjir = (int *) malloc(mxGetNzmax(prhs[imi])*sizeof(int));
+			for (i=0; i<mxGetNzmax(prhs[imi]); i++)
+				adjir[i]=(int)ir[i];
+		}
+		if (mxGetN(prhs[imi])) {
+			jc    =mxGetJc(prhs[imi]);
+			adjjc = (int *) malloc((mxGetN(prhs[imi])+1)*sizeof(int));
+			for (i=0; i<(mxGetN(prhs[imi])+1); i++)
+				adjjc[i]=(int)jc[i];
+		}
+		mexPrintf("%s -- Adjacency matrix is of size %d by %d with %d non-zeroes.\n",
+				  __FUNCT__,mxGetM(prhs[imi]),mxGetN(prhs[imi]),mxGetNzmax(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex label vector must be numeric.\n",__FUNCT__);
+		mexErrMsgTxt(" ");
+	}
+	else {
+		if (mxGetM(prhs[imi])*mxGetN(prhs[imi])) {
+			vld=mxGetPr(prhs[imi]);
+			vli = (int *) malloc(mxGetM(prhs[imi])*mxGetN(prhs[imi])*sizeof(int));
+			for (i=0; i<mxGetM(prhs[imi])*mxGetN(prhs[imi]); i++)
+				vli[i]=(int)vld[i];
+		}
+		mexPrintf("%s -- Vertex label vector is of size %d by %d.\n",
+				  __FUNCT__,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi])) {
+		mexPrintf("%s -- Vertex weight vector must be numeric.\n",__FUNCT__);
+		mexErrMsgTxt(" ");
+	}
+	else {
+		if (mxGetM(prhs[imi])*mxGetN(prhs[imi])) {
+			vwd=mxGetPr(prhs[imi]);
+			vwi = (int *) malloc(mxGetM(prhs[imi])*mxGetN(prhs[imi])*sizeof(int));
+			for (i=0; i<mxGetM(prhs[imi])*mxGetN(prhs[imi]); i++)
+				vwi[i]=(int)vwd[i];
+		}
+		mexPrintf("%s -- Vertex weight vector is of size %d by %d.\n",
+				  __FUNCT__,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+	}
+	imi++;
+
+	if (!mxIsNumeric(prhs[imi]) || (!mxIsEmpty(prhs[imi]) && !mxIsSparse(prhs[imi]))) {
+		mexPrintf("%s -- Edge weight matrix must be numeric and sparse.\n",__FUNCT__);
+		mexErrMsgTxt(" ");
+	}
+	else {
+		if (mxGetM(prhs[imi])) {
+			ewd=mxGetPr(prhs[imi]);
+			ewi = (int *) malloc(mxGetM(prhs[imi])*sizeof(int));
+			for (i=0; i<mxGetNzmax(prhs[imi]); i++)
+				ewi[i]=(int)ewd[i];
+		}
+		mexPrintf("%s -- Edge weight matrix is of size %d by %d with %d non-zeroes.\n",
+				  __FUNCT__,mxGetM(prhs[imi]),mxGetN(prhs[imi]),mxGetNzmax(prhs[imi]));
+	}
+	imi++;
+
+	if (!((strlen (argvm[0]) >= 5) &&
+		  (strncmp (argvm[0] + strlen (argvm[0]) - 5, "gpart", 5) == 0))) {
+		if (!mxIsChar(prhs[imi])) {
+			mexPrintf("%s -- Architecture type must be character.\n",__FUNCT__);
+			mexErrMsgTxt(" ");
+		}
+		else {
+			if (mxGetM(prhs[imi])*mxGetN(prhs[imi])) {
+				archtyp = (char *) calloc(mxGetM(prhs[imi])*mxGetN(prhs[imi])+1,sizeof(char));
+				mxGetString(prhs[imi],archtyp,mxGetM(prhs[imi])*mxGetN(prhs[imi])+1);
+			}
+			mexPrintf("%s -- Architecture type is \"%s\".\n",
+					  __FUNCT__,archtyp);
+		}
+		imi++;
+
+		if (!mxIsNumeric(prhs[imi])) {
+			mexPrintf("%s -- Architecture parameter vector must be numeric.\n",__FUNCT__);
+			mexErrMsgTxt(" ");
+		}
+		else {
+			napar =mxGetM(prhs[imi])*mxGetN(prhs[imi]);
+			if (mxGetM(prhs[imi])*mxGetN(prhs[imi])) {
+				apd=mxGetPr(prhs[imi]);
+				api = (int *) malloc(mxGetM(prhs[imi])*mxGetN(prhs[imi])*sizeof(int));
+				for (i=0; i<mxGetM(prhs[imi])*mxGetN(prhs[imi]); i++)
+					api[i]=(int)apd[i];
+			}
+			mexPrintf("%s -- Architecture parameter vector is of size %d by %d.\n",
+					  __FUNCT__,mxGetM(prhs[imi]),mxGetN(prhs[imi]));
+		}
+		imi++;
+	}
+
+	while (imi < nrhs) {
+		if (!mxIsChar(prhs[imi])) {
+			mexPrintf("%s -- prhs[%d] must be character.\n",__FUNCT__,imi);
+			mexErrMsgTxt(" ");
+		}
+		else {
+			argvm[isi] = (char *) calloc(mxGetM(prhs[imi])*mxGetN(prhs[imi])+1,sizeof(char));
+			mxGetString(prhs[imi],argvm[isi],mxGetM(prhs[imi])*mxGetN(prhs[imi])+1);
+		}
+		isi++;
+		imi++;
+	}
+	argcm=isi;
+	mexPrintf("argcm=%d\n",argcm);
+	for (i=0; i<argcm; i++)
+		mexPrintf("argvm[%d]=\"%s\"\n",i,argvm[i]);
+
+	/* Do the actual computations in a subroutine */
+
+	mexPrintf("Gmapx:\n");
+	ierr=gmapx(&maptabi,
+			   argcm,
+			   argvm,
+			   nvert,
+			   nedge2,
+			   adjir,
+			   adjjc,
+			   vli,
+			   vwi,
+			   ewi,
+			   archtyp,
+			   napar,
+			   api);
+	mexPrintf("%s -- Error %d from Gmapx.\n",__FUNCT__,ierr);
+
+/*  for (i=0; i<nvert; i++)
+		mexPrintf("maptabi[%d][0]=%d, maptabi[%d][1]=%d\n",
+			 	  i,maptabi[i][0],i,maptabi[i][1]); */
+
+	/* Create matrices for the return arguments */
+
+	if (maptabi) {
+		plhs[imo]=mxCreateDoubleMatrix(nvert, 2, mxREAL);
+		maptabd = mxGetPr(plhs[imo]);
+		k=0;
+		for (j=0; j<2; j++)
+			for (i=0; i<nvert; i++)
+				maptabd[k++]=(double)maptabi[i][j];
+		//free(maptabi);
+	}
+	else {
+		plhs[imo]=mxCreateDoubleMatrix(0, 2, mxREAL);
+	}
+	imo++;
+
+	/*if (argvm)
+		for (i=argcm-1; i>=0; i--)
+			free(argvm[i]);
+	if (api)     free(api);
+	if (archtyp) free(archtyp);
+	if (ewi)     free(ewi);
+	if (vwi)     free(vwi);
+	if (vli)     free(vli);
+	if (adjjc)   free(adjjc);
+	if (adjir)   free(adjir);*/
+
+	return;
+#endif //#ifndef _HAVE_SCOTCH_
+}
Index: /issm/trunk/src/wrappers/Scotch/Scotch.h
===================================================================
--- /issm/trunk/src/wrappers/Scotch/Scotch.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Scotch/Scotch.h	(revision 13975)
@@ -0,0 +1,35 @@
+/*!\file:  Scotch.h
+ * \brief header file for Scotch module.
+ */ 
+
+#ifndef _SCOTCH_H
+#define _SCOTCH_H
+
+#include <stdio.h>
+#include <string.h>    /*  strcasecmp  */
+#include <time.h>      /*  clock,time,difftime  */
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+    
+#undef __FUNCT__ 
+#define __FUNCT__  "Scotch"
+
+/*  Scotch structures and prototypes  */
+#ifdef MATLAB
+#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)
+#endif
+
+#endif  /* _SCOTCH_H */
Index: /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp
===================================================================
--- /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.cpp	(revision 13975)
@@ -0,0 +1,99 @@
+/*\file Shp2Kml.c
+ *\brief: shp to kml file conversion mex module.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./Shp2Kml.h"
+
+void Shp2KmlUsage(void){/*{{{*/
+	_pprintLine_("Shp2Kml - shp to kml file conversion module:");
+	_pprintLine_("");
+	_pprintLine_("   This module converts a file from shp to kml format.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [ret]=Shp2Kml(filshp,filkml,sgn,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      filshp      file name of shp file to be read (char, extension optional)");
+	_pprintLine_("      filkml      file name of kml file to be written (char)");
+	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north); -1 (south); or 0 (no translation))");
+	_pprintLine_("");
+	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
+	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
+	_pprintLine_("");
+	_pprintLine_("      ret         return code (non-zero for warning)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml', 0);");
+	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml', 1,'central_meridian',45,'standard_parallel',70);");
+	_pprintLine_("      [ret]=Shp2Kml('file.shp','file.kml',-1,'central_meridian', 0,'standard_parallel',71);");
+	_pprintLine_("");
+}/*}}}*/
+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/wrappers/Shp2Kml/Shp2Kml.h
===================================================================
--- /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Shp2Kml/Shp2Kml.h	(revision 13975)
@@ -0,0 +1,53 @@
+/*!\file Shp2Kml.h
+ * \brief: prototype for shp to kml file conversion mex module.
+ */
+
+#ifndef _SHP2KML_H
+#define _SHP2KML_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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 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: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  1
+
+#endif
+
Index: /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp
===================================================================
--- /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/StringToEnum/StringToEnum.cpp	(revision 13975)
@@ -0,0 +1,34 @@
+/*\file StringToEnum.c
+ *\brief:convert enum (int) to string
+ */
+
+#include "./StringToEnum.h"
+
+void StringToEnumUsage(void){/*{{{*/
+	_pprintLine_("");
+	_pprintLine_("   usage: " << __FUNCT__ << "enum = StringToEnum(string);");
+	_pprintLine_("");
+}/*}}}*/
+WRAPPER(StringToEnum){
+
+	char    *name    = NULL;
+	int      enum_out;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&StringToEnumUsage);
+
+	/*Fetch inputs: */
+	FetchData(&name,NAME);
+
+	/*Run core function: */
+	enum_out=StringToEnumx(name);
+
+	/* output: */
+	WriteData(ENUMOUT,enum_out);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h
===================================================================
--- /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h	(revision 13975)
+++ /issm/trunk/src/wrappers/StringToEnum/StringToEnum.h	(revision 13975)
@@ -0,0 +1,49 @@
+/*!\file:  StringToEnum.h
+ * \brief header file for StringToEnum module.
+ */ 
+
+#ifndef _STRINGTOENUM_H
+#define _STRINGTOENUM_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.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: */
+#undef NLHS
+#define NLHS  1
+#undef NRHS
+#define NRHS  1
+
+#endif  /* _TEST_H */
Index: /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/TriMesh/TriMesh.cpp	(revision 13975)
@@ -0,0 +1,62 @@
+/*
+ * TriMesh: mesh a domain using an .exp file
+ */
+
+#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){
+	
+	/*intermediary: */
+	double  area;
+	DataSet *domain = NULL;
+	DataSet *rifts  = NULL;
+
+	/* output: */
+	SeqMat<double> *index             = NULL;
+	SeqVec<double> *x                 = NULL;
+	SeqVec<double> *y                 = NULL;
+	SeqMat<double> *segments          = NULL;
+	SeqVec<double> *segmentmarkerlist = NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments: */
+	CHECKARGUMENTS(NLHS,NRHS,&TriMeshUsage);
+	
+	/*Fetch data needed for meshing: */
+	FetchData(&domain,DOMAINOUTLINE);
+	FetchData(&rifts,RIFTSOUTLINE);
+	FetchData(&area,AREA);
+
+	/*call x core: */
+	TriMeshx(&index,&x,&y,&segments,&segmentmarkerlist,domain,rifts,area);
+
+	/*write outputs: */
+	WriteData(INDEX,index);
+	WriteData(X,x);
+	WriteData(Y,y);
+	WriteData(SEGMENTS,segments);
+	WriteData(SEGMENTMARKERLIST,segmentmarkerlist);
+
+	/*free ressources: */
+	delete domain;
+	delete rifts;
+	delete index;
+	delete x;
+	delete y;
+	delete segments;
+	delete segmentmarkerlist;
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/TriMesh/TriMesh.h
===================================================================
--- /issm/trunk/src/wrappers/TriMesh/TriMesh.h	(revision 13975)
+++ /issm/trunk/src/wrappers/TriMesh/TriMesh.h	(revision 13975)
@@ -0,0 +1,65 @@
+/*
+	TriMesh.h
+*/
+
+#ifndef _TRIMESH_H
+#define _TRIMESH_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+/*Header files: */
+#include "../../c/include/globals.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/include/include.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+#include "../../c/io/io.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "TriMesh"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define DOMAINOUTLINE  prhs[0]
+#define RIFTSOUTLINE   prhs[1]
+#define AREA           prhs[2]
+/* serial output macros: */
+#define INDEX             (mxArray**)&plhs[0]
+#define X                 (mxArray**)&plhs[1]
+#define Y                 (mxArray**)&plhs[2]
+#define SEGMENTS          (mxArray**)&plhs[3]
+#define SEGMENTMARKERLIST (mxArray**)&plhs[4]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define DOMAINOUTLINE PyTuple_GetItem(args,0)
+#define RIFTSOUTLINE  PyTuple_GetItem(args,1)
+#define AREA          PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define INDEX             output,0
+#define X                 output,1
+#define Y                 output,2
+#define SEGMENTS          output,3
+#define SEGMENTMARKERLIST output,4
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  5
+#undef NRHS
+#define NRHS  3
+
+#endif  /* _TRIMESH_H */
Index: /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.cpp	(revision 13975)
@@ -0,0 +1,53 @@
+/*!\file:  TriMeshProcessRifts.cpp
+ * \brief split a mesh where a rift (or fault) is present
+ */ 
+
+#include "./TriMeshProcessRifts.h"
+
+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){
+
+	/* returned quantities: */
+	RiftStruct *riftstruct = NULL;
+
+	/* input: */
+	int     nel,nods;
+	double *index          = NULL;
+	double *x              = NULL;
+	double *y              = NULL;
+	double *segments       = NULL;
+	double *segmentmarkers = NULL;
+	int     num_seg;
+
+	/*Boot module*/
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CHECKARGUMENTS(NLHS,NRHS,&TriMeshProcessRiftsUsage);
+
+	/*Fetch data */
+	FetchData(&index,&nel,NULL,INDEXIN);
+	FetchData(&x,&nods,XIN);
+	FetchData(&y,NULL,YIN);
+	FetchData(&segments,&num_seg,NULL,SEGMENTSIN);
+	FetchData(&segmentmarkers,NULL,SEGMENTMARKERSIN);
+
+	/*call x layer*/
+	TriMeshProcessRiftsx(&index,&nel,&x,&y,&nods,&segments,&segmentmarkers,&num_seg,&riftstruct);
+
+	/*Output : */
+	WriteData(INDEXOUT,index,nel,3);
+	WriteData(XOUT,x,nods,1);
+	WriteData(YOUT,y,nods,1);
+	WriteData(SEGMENTSOUT,segments,num_seg,3);
+	WriteData(SEGMENTMARKERSOUT,segmentmarkers,num_seg,1);
+	WriteData(RIFTSTRUCT,riftstruct);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h
===================================================================
--- /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 13975)
+++ /issm/trunk/src/wrappers/TriMeshProcessRifts/TriMeshProcessRifts.h	(revision 13975)
@@ -0,0 +1,66 @@
+/*
+ * TriMeshProcessRifts.h
+ */ 
+
+#ifndef _TRIMESH_PROCESSRIFTS_H_
+#define _TRIMESH_PROCESSRIFTS_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#define __FUNCT__  "TriMeshProcessRifts"
+
+#ifdef _HAVE_MATLAB_MODULES_
+/* serial input macros: */
+#define INDEXIN          prhs[0]
+#define XIN              prhs[1]
+#define YIN              prhs[2]
+#define SEGMENTSIN       prhs[3]
+#define SEGMENTMARKERSIN prhs[4]
+/* serial output macros: */
+#define INDEXOUT          (mxArray**)&plhs[0]
+#define XOUT              (mxArray**)&plhs[1]
+#define YOUT              (mxArray**)&plhs[2]
+#define SEGMENTSOUT       (mxArray**)&plhs[3]
+#define SEGMENTMARKERSOUT (mxArray**)&plhs[4]
+#define RIFTSTRUCT        (mxArray**)&plhs[5]
+#endif
+
+#ifdef _HAVE_PYTHON_MODULES_
+/* serial input macros: */
+#define INDEXIN          PyTuple_GetItem(args,0)
+#define XIN              PyTuple_GetItem(args,1)
+#define YIN              PyTuple_GetItem(args,2)
+#define SEGMENTSIN       PyTuple_GetItem(args,3)
+#define SEGMENTMARKERSIN PyTuple_GetItem(args,4)
+/* serial output macros: */
+#define INDEXOUT          output,0
+#define XOUT              output,1
+#define YOUT              output,2
+#define SEGMENTSOUT       output,3
+#define SEGMENTMARKERSOUT output,4
+#define RIFTSTRUCT        output,5
+#endif
+
+/* serial arg counts: */
+#undef NLHS
+#define NLHS  6
+#undef NRHS
+#define NRHS  5
+
+#endif
Index: /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp
===================================================================
--- /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/TriaSearch/TriaSearch.cpp	(revision 13975)
@@ -0,0 +1,60 @@
+/*\file TriaSearch.c
+ *\brief: TriaSearch module. See TriaSearchx for more details.
+ */
+#include "./TriaSearch.h"
+
+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;
+
+	/*input: */
+	int*    index=NULL;
+	int     nel;
+	int     dummy;
+
+	double* x=NULL;
+	double* y=NULL;
+	int     nods;
+
+	double* x0=NULL;
+	double* y0=NULL;
+	int     numberofnodes;
+
+	/* output: */
+	double*  tria=NULL;
+
+	/*Boot module: */
+	MODULEBOOT();
+
+	/*checks on arguments on the matlab side: */
+	CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,&TriaSearchUsage);
+
+	/*Input datasets: */
+	FetchData(&index,&nel,&dummy,INDEXHANDLE);
+	FetchData(&x,&nods,XHANDLE);
+	FetchData(&y,&nods,YHANDLE);
+	FetchData(&x0,&numberofnodes,X0HANDLE);
+	FetchData(&y0,&numberofnodes,Y0HANDLE);
+
+	/* Run core computations: */
+	TriaSearchx(&tria,index,nel,x,y,nods,x0,y0,numberofnodes);
+
+	/* c to matlab: */
+	for(i=0;i<numberofnodes;i++)tria[i]++;
+
+	/*Write data: */
+	WriteData(TRIA,tria,numberofnodes);
+
+	/*end module: */
+	MODULEEND();
+}
Index: /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h
===================================================================
--- /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h	(revision 13975)
+++ /issm/trunk/src/wrappers/TriaSearch/TriaSearch.h	(revision 13975)
@@ -0,0 +1,57 @@
+/*!\file TriaSearch.h
+ */
+
+#ifndef _TRIASEARCH_H
+#define _TRIASEARCH_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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]
+
+/* 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
+
+#endif
Index: /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp
===================================================================
--- /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/Xy2ll/Xy2ll.cpp	(revision 13975)
@@ -0,0 +1,96 @@
+/*\file Xy2ll.c
+ *\brief: x/y to lat/long coordinate mex module.
+ */
+#include "./Xy2ll.h"
+
+void Xy2llUsage(void){/*{{{*/
+	_pprintLine_("Xy2ll - x/y to lat/long coordinate transformation module:");
+	_pprintLine_("");
+	_pprintLine_("   This module transforms x/y to lat/long coordinates.");
+	_pprintLine_("");
+	_pprintLine_("   Usage:");
+	_pprintLine_("      [lat,lon]=Xy2ll(x,y,sgn,'param name',param,...);");
+	_pprintLine_("");
+	_pprintLine_("      x           x coordinates (double vector)");
+	_pprintLine_("      y           y coordinates (double vector)");
+	_pprintLine_("      sgn         sign for hemisphere (double, +1 (north) or -1 (south))");
+	_pprintLine_("");
+	_pprintLine_("      central_meridian     central meridian (double, optional, but must specify with sp)");
+	_pprintLine_("      standard_parallel    standard parallel (double, optional, but must specify with cm)");
+	_pprintLine_("");
+	_pprintLine_("      lat         latitude coordinates (double vector)");
+	_pprintLine_("      lon         longitude coordinates (double vector)");
+	_pprintLine_("");
+	_pprintLine_("   Examples:");
+	_pprintLine_("      [lat,lon]=Xy2ll(x,y, 1);");
+	_pprintLine_("      [lat,lon]=Xy2ll(x,y, 1,'central_meridian',45,'standard_parallel',70);");
+	_pprintLine_("      [lat,lon]=Xy2ll(x,y,-1,'central_meridian', 0,'standard_parallel',71);");
+	_pprintLine_("");
+}/*}}}*/
+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/wrappers/Xy2ll/Xy2ll.h
===================================================================
--- /issm/trunk/src/wrappers/Xy2ll/Xy2ll.h	(revision 13975)
+++ /issm/trunk/src/wrappers/Xy2ll/Xy2ll.h	(revision 13975)
@@ -0,0 +1,54 @@
+/*!\file Xy2ll.h
+ * \brief: prototype for x/y to lat/long coordinate mex module.
+ */
+
+#ifndef _XY2LL_H
+#define _XY2LL_H
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+	#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*For python modules: needs to come before header files inclusion*/
+#ifdef _HAVE_PYTHON_
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#endif
+
+#include "../../c/include/globals.h"
+#include "../../c/modules/modules.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../bindings.h"
+
+#undef __FUNCT__ 
+#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   PyTuple_GetItem(args,0)
+#define Y_IN   PyTuple_GetItem(args,1)
+#define SGN_IN PyTuple_GetItem(args,2)
+/* serial output macros: */
+#define LAT_OUT output,0
+#define LON_OUT output,1
+#endif
+
+/* serial arg counts: */
+#undef NRHS
+#define NRHS  3
+#undef NLHS
+#define NLHS  2
+
+#endif
Index: /issm/trunk/src/wrappers/bindings.h
===================================================================
--- /issm/trunk/src/wrappers/bindings.h	(revision 13975)
+++ /issm/trunk/src/wrappers/bindings.h	(revision 13975)
@@ -0,0 +1,22 @@
+#ifndef _BINDINGS_H_
+#define _BINDINGS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef  _HAVE_MATLAB_MODULES_
+#include "./matlab/include/matlabincludes.h"
+#include "./matlab/include/wrapper_macros.h"
+#include "./matlab/io/matlabio.h"
+#endif
+
+#ifdef  _HAVE_PYTHON_MODULES_
+#include "./python/include/pythonincludes.h"
+#include "./python/include/wrapper_macros.h"
+#include "./python/io/pythonio.h"
+#endif
+
+#endif
Index: /issm/trunk/src/wrappers/include/issm-binding.h
===================================================================
--- /issm/trunk/src/wrappers/include/issm-binding.h	(revision 13975)
+++ /issm/trunk/src/wrappers/include/issm-binding.h	(revision 13975)
@@ -0,0 +1,18 @@
+#ifndef _ISSM_BINDING_H_
+#define _ISSM_BINDING_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef  _HAVE_MATLAB_MODULES_
+#include "../matlab/include/matlab-macros.h"
+#endif
+
+#ifdef  _HAVE_PYTHON_MODULES_
+#include "../python/include/python-macros.h"
+#endif
+
+#endif
Index: /issm/trunk/src/wrappers/matlab/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/Makefile.am	(revision 13975)
@@ -0,0 +1,263 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @MATLABINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@
+
+EXEEXT=$(MATLABWRAPPEREXT)
+
+#matlab io{{{
+lib_LIBRARIES = libISSMMatlab.a 
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMMatlab.la
+else
+lib_LTLIBRARIES =
+endif
+
+io_sources= ./include/matlabincludes.h\
+				./io/matlabio.h\
+				./io/MatlabNArrayToNArray.cpp\
+				./io/CheckNumMatlabArguments.cpp\
+				./io/mxGetAssignedField.cpp\
+				./io/WriteMatlabData.cpp\
+				./io/FetchMatlabData.cpp\
+				./io/OptionParse.cpp\
+				./io/MatlabMatrixToMatrix.cpp\
+				./io/MatlabVectorToVector.cpp\
+				./io/MatlabVectorToDoubleVector.cpp\
+				./io/MatlabMatrixToDoubleMatrix.cpp\
+				./io/MatlabMatrixToSeqMat.cpp\
+				./io/MatlabVectorToSeqVec.cpp
+				
+if PETSC
+io_sources += ./io/MatlabMatrixToPetscMat.cpp\
+				./io/MatlabVectorToPetscVec.cpp
+endif
+
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_ -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+libISSMMatlab_a_SOURCES = $(io_sources)
+libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMMatlab_la_SOURCES = $(io_sources)
+endif
+#}}}
+#Wrappers {{{
+if WRAPPERS
+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 {{{
+#if SHAREDLIBS
+#deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
+#else
+#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+#endif
+#deps +=  $(MATHLIB) ${MEXLIB}
+deps =  $(MATHLIB) ${MEXLIB}
+
+#Triangle library
+AM_CXXFLAGS =  -DTRILIBRARY -DANSI_DECLARATORS -DNO_TIMER -D_WRAPPERS_
+
+#Matlab part
+AM_LDFLAGS = -module $(MEXLINK) -shrext ${EXEEXT}  -L/usr/lib
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+if SHAREDLIBS
+deps += ./libISSMMatlab.la 
+else
+deps += ./libISSMMatlab.a
+AM_LDFLAGS += --no-warnings 
+endif
+
+AM_CXXFLAGS +=  -D_HAVE_MATLAB_MODULES_  -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread 
+
+if SHAREDLIBS
+deps +=
+else
+deps += ../../c/libISSMModules.a ../../c/libISSMCore.a  
+if ADOLC
+deps += $(ADOLCLIB)
+endif
+endif
+#Optimization flags:
+AM_CXXFLAGS += $(CXXOPTFLAGS) 
+#}}}
+#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
+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) $(MPILIB)
+
+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/wrappers/matlab/include/matlabincludes.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/include/matlabincludes.h	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/include/matlabincludes.h	(revision 13975)
@@ -0,0 +1,15 @@
+
+#ifndef _MATLAB_INCLUDES_H_
+#define _MATLAB_INCLUDES_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_MATLAB_
+#include <mex.h>
+#endif
+
+#endif /*_MATLAB_INCLUDES_H_*/
Index: /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/include/wrapper_macros.h	(revision 13975)
@@ -0,0 +1,42 @@
+/* \file matlab macros.h
+ * \brief: macros used for the matlab bindings
+ */
+
+#ifndef _MATLAB_MACROS_H_
+#define _MATLAB_MACROS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_MATLAB_
+/* MODULEBOOT/MODULEEND {{{*/
+
+/*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*/
+#define MODULEBOOT(); try{ \
+	IssmComm::SetComm(-1);
+
+#define MODULEEND(); }\
+	catch(ErrorException &exception){\
+		mexErrMsgTxt(exception.MatlabReport()); \
+	}\
+	catch (exception &e){\
+		mexErrMsgTxt(exprintf("Standard exception: %s\n",e.what()));\
+	}\
+	catch(...){\
+		mexErrMsgTxt("An unexpected error occurred");\
+	}
+/*}}}*/
+/* WRAPPER {{{*/
+#define WRAPPER(modulename,...) void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) 
+/*}}}*/
+/* CHECKARGUMENTS {{{*/
+#define CHECKARGUMENTS(NLHS,NRHS,functionpointer) CheckNumMatlabArguments(nlhs,NLHS,nrhs,NRHS,__FUNCT__,functionpointer)
+/*}}}*/
+#endif
+
+#endif
Index: /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/CheckNumMatlabArguments.cpp	(revision 13975)
@@ -0,0 +1,23 @@
+/*!\file CheckNumMatlabArguments.cpp:
+ * \brief: check number of arguments and report an usage error message.
+ */
+
+#include "./matlabio.h"
+#include "../../c/shared/Exceptions/exceptions.h"
+
+int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void )){
+
+	/*checks on arguments on the matlab side: */
+	if (nrhs==0 && nlhs==0) {
+		/*unless NLHS=0 and NRHS=0, we are just asking for documentation: */
+		if (NRHS==0 && NLHS==0)return 1;
+		/* special case: */
+		function();
+		_error_("usage: see above");
+	}
+	else if (nlhs!=NLHS || nrhs!=NRHS ) {
+		function(); 
+		_error_("usage error.");
+	}
+	return 1;
+}
Index: /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/FetchMatlabData.cpp	(revision 13975)
@@ -0,0 +1,691 @@
+/*\file FetchData.cpp:
+ * \brief: general I/O interface to fetch data in matlab
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+
+/*Primitive data types*/
+/*FUNCTION FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){{{*/
+void FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref){
+
+	double*  outmatrix=NULL;
+	int      outmatrix_rows,outmatrix_cols;
+
+	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(&outmatrix,&outmatrix_rows,&outmatrix_cols,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 (pM)*pM=outmatrix_rows;
+	if (pN)*pN=outmatrix_cols;
+
+}
+/*}}}*/
+/*FUNCTION FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{*/
+void FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
+
+	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) ){
+		/*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!: */
+		_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(double** pvector,int* pM,const mxArray* dataref){{{*/
+void FetchData(double** pvector,int* pM,const mxArray* dataref){
+
+	double* outvector=NULL;
+	int outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&outvector,&outvector_rows,dataref);
+
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchData(int** pvector,int* pM,const mxArray* dataref){{{*/
+void FetchData(int** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	int    *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into integer vector: */
+		outvector=xNew<int>(outvector_rows);
+		for(i=0;i<outvector_rows;i++)outvector[i]=(int)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool** pvector,int* pM,const mxArray* dataref){{{*/
+void FetchData(bool** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	bool   *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into integer vector: */
+		outvector=xNew<bool>(outvector_rows);
+		for(i=0;i<outvector_rows;i++)outvector[i]=(bool)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchData(float** pvector,int* pM,const mxArray* dataref){{{*/
+void FetchData(float** pvector,int* pM,const mxArray* dataref){
+
+	int    i;
+	double *doublevector   = NULL;
+	float  *outvector      = NULL;
+	int     outvector_rows;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		outvector_rows=0;
+		outvector=NULL;
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to double*  vector: */
+		MatlabVectorToDoubleVector(&doublevector,&outvector_rows,dataref);
+
+		/*Convert double vector into float vector: */
+		outvector=xNew<float>(outvector_rows);
+		for(i=0;i<outvector_rows;i++)outvector[i]=(float)doublevector[i];
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pvector=outvector;
+	if (pM)*pM=outvector_rows;
+}
+/*}}}*/
+/*FUNCTION FetchData(char** pstring,const mxArray* dataref){{{*/
+void FetchData(char** pstring,const mxArray* dataref){
+
+	char* outstring=NULL;
+
+	/*Ok, the string should be coming directly from the matlab workspace: */
+	if (!mxIsClass(dataref,"char")){
+		_error_("input data_type is not a string!");
+	}
+	else{
+		/*Recover the string:*/
+		int stringlen;
+
+		stringlen = mxGetM(dataref)*mxGetN(dataref)+1;
+		outstring =xNew<char>(stringlen);
+		mxGetString(dataref,outstring,stringlen);
+	}
+
+	/*Assign output pointers:*/
+	*pstring=outstring;
+}/*}}}*/
+/*FUNCTION FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){{{*/
+void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref){
+
+	int      outmatrix_numel,outmatrix_ndims;
+	int*     outmatrix_size=NULL;
+	char*    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,"char") ){
+
+		/*Convert matlab n-dim array to char* 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(double* pscalar,const mxArray* dataref){{{*/
+void FetchData(double* pscalar,const mxArray* dataref){
+
+	double scalar;
+
+	if (!mxIsClass(dataref,"double")){
+		_error_("input data_type is not a double!");
+	}
+	else{
+		/*Recover the double: */
+		scalar=mxGetScalar(dataref);
+	}
+
+	/*Assign output pointers:*/
+	*pscalar=scalar;
+}
+/*}}}*/
+/*FUNCTION FetchData(int* pinteger,const mxArray* dataref){{{*/
+void FetchData(int* pinteger,const mxArray* dataref){
+
+	int integer;
+
+	if (!mxIsClass(dataref,"double")){
+		_error_("input data_type is not a scalar!");
+	}
+	else{
+		/*Recover the double: */
+		integer=(int)mxGetScalar(dataref);
+	}
+
+	/*Assign output pointers:*/
+	*pinteger=integer;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool* pboolean,const mxArray* dataref){{{*/
+void FetchData(bool* pboolean,const mxArray* dataref){
+
+	bool* mxbool_ptr=NULL;
+
+	if (mxIsClass(dataref,"logical")){
+		if(mxGetM(dataref)!=1) _error_("input data is not of size 1x1");
+		if(mxGetN(dataref)!=1) _error_("input data is not of size 1x1");
+		mxbool_ptr=mxGetLogicals(dataref);
+	}
+	else{
+		_error_("input data_type is not a bool!");
+	}
+
+	*pboolean=*mxbool_ptr;
+}
+/*}}}*/
+
+/*ISSM objects*/
+/*FUNCTION FetchData(Matrix<double>** pmatrix,const mxArray* dataref){{{*/
+void FetchData(Matrix<double>** pmatrix,const mxArray* dataref){
+
+	Matrix<double>* outmatrix=NULL;
+	int dummy=0;
+
+	if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab matrix to matrix: */
+		outmatrix=MatlabMatrixToMatrix(dataref);
+
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pmatrix=outmatrix;
+}
+/*}}}*/
+/*FUNCTION FetchData(Vector<double>** pvector,const mxArray* dataref){{{*/
+void FetchData(Vector<double>** pvector,const mxArray* dataref){
+
+	Vector<double>* vector=NULL;
+	int dummy;
+
+	if(mxIsEmpty(dataref)){
+		/*Nothing to pick up. Just initialize matrix pointer to NULL: */
+		vector=new Vector<double>(0);
+	}
+	else if (mxIsClass(dataref,"double") ){
+
+		/*Convert matlab vector to petsc vector: */
+		vector=MatlabVectorToVector(dataref);
+	}
+	else{
+		/*This is an error: we don't have the correct input!: */
+		_error_("Input parameter of class " << mxGetClassName(dataref) << " not supported yet");
+	}
+
+	/*Assign output pointers:*/
+	*pvector=vector;
+}
+/*}}}*/
+/*FUNCTION FetchData(BamgGeom** pbamggeom,const mxArray* dataref){{{*/
+void FetchData(BamgGeom** pbamggeom,const mxArray* dataref){
+
+	/*Initialize output*/
+	BamgGeom* bamggeom=new BamgGeom();
+
+	/*Fetch all fields*/
+	FetchData(&bamggeom->Vertices,&bamggeom->VerticesSize[0],&bamggeom->VerticesSize[1],mxGetAssignedField(dataref,0,"Vertices"));
+	FetchData(&bamggeom->Edges, &bamggeom->EdgesSize[0], &bamggeom->EdgesSize[1], mxGetAssignedField(dataref,0,"Edges"));
+	FetchData(&bamggeom->Corners, &bamggeom->CornersSize[0], &bamggeom->CornersSize[1], mxGetAssignedField(dataref,0,"Corners"));
+	FetchData(&bamggeom->RequiredVertices,&bamggeom->RequiredVerticesSize[0],&bamggeom->RequiredVerticesSize[1],mxGetAssignedField(dataref,0,"RequiredVertices"));
+	FetchData(&bamggeom->RequiredEdges, &bamggeom->RequiredEdgesSize[0], &bamggeom->RequiredEdgesSize[1], mxGetAssignedField(dataref,0,"RequiredEdges"));
+	FetchData(&bamggeom->CrackedEdges,&bamggeom->CrackedEdgesSize[0],&bamggeom->CrackedEdgesSize[1],mxGetAssignedField(dataref,0,"CrackedEdges"));
+	FetchData(&bamggeom->SubDomains,&bamggeom->SubDomainsSize[0],&bamggeom->SubDomainsSize[1],mxGetAssignedField(dataref,0,"SubDomains"));
+
+	/*Assign output pointers:*/
+	*pbamggeom=bamggeom;
+}
+/*}}}*/
+/*FUNCTION FetchData(BamgMesh** pbamgmesh,const mxArray* dataref){{{*/
+void FetchData(BamgMesh** pbamgmesh,const mxArray* dataref){
+
+	/*Initialize output*/
+	BamgMesh* bamgmesh=new BamgMesh();
+
+	/*Fetch all fields*/
+	FetchData(&bamgmesh->Vertices,&bamgmesh->VerticesSize[0],&bamgmesh->VerticesSize[1],mxGetAssignedField(dataref,0,"Vertices"));
+	FetchData(&bamgmesh->Edges, &bamgmesh->EdgesSize[0], &bamgmesh->EdgesSize[1], mxGetAssignedField(dataref,0,"Edges"));
+	FetchData(&bamgmesh->Triangles, &bamgmesh->TrianglesSize[0], &bamgmesh->TrianglesSize[1], mxGetAssignedField(dataref,0,"Triangles"));
+	FetchData(&bamgmesh->CrackedEdges,&bamgmesh->CrackedEdgesSize[0],&bamgmesh->CrackedEdgesSize[1],mxGetAssignedField(dataref,0,"CrackedEdges"));
+	FetchData(&bamgmesh->VerticesOnGeomEdge,&bamgmesh->VerticesOnGeomEdgeSize[0],&bamgmesh->VerticesOnGeomEdgeSize[1],mxGetAssignedField(dataref,0,"VerticesOnGeomEdge"));
+	FetchData(&bamgmesh->VerticesOnGeomVertex,&bamgmesh->VerticesOnGeomVertexSize[0],&bamgmesh->VerticesOnGeomVertexSize[1],mxGetAssignedField(dataref,0,"VerticesOnGeomVertex"));
+	FetchData(&bamgmesh->EdgesOnGeomEdge, &bamgmesh->EdgesOnGeomEdgeSize[0], &bamgmesh->EdgesOnGeomEdgeSize[1], mxGetAssignedField(dataref,0,"EdgesOnGeomEdge"));
+	FetchData(&bamgmesh->IssmSegments,&bamgmesh->IssmSegmentsSize[0],&bamgmesh->IssmSegmentsSize[1],mxGetAssignedField(dataref,0,"IssmSegments"));
+
+	/*Assign output pointers:*/
+	*pbamgmesh=bamgmesh;
+}
+/*}}}*/
+/*FUNCTION FetchData(BamgOpts** pbamgopts,const mxArray* dataref){{{*/
+void FetchData(BamgOpts** pbamgopts,const mxArray* dataref){
+
+	/*Initialize output*/
+	BamgOpts* bamgopts=new BamgOpts();
+
+	/*Fetch all fields*/
+	FetchData(&bamgopts->anisomax,mxGetField(dataref,0,"anisomax"));
+	FetchData(&bamgopts->cutoff,mxGetField(dataref,0,"cutoff"));
+	FetchData(&bamgopts->coeff,mxGetField(dataref,0,"coeff"));
+	FetchData(&bamgopts->errg,mxGetField(dataref,0,"errg"));
+	FetchData(&bamgopts->gradation,mxGetField(dataref,0,"gradation"));
+	FetchData(&bamgopts->Hessiantype,mxGetField(dataref,0,"Hessiantype"));
+	FetchData(&bamgopts->MaxCornerAngle,mxGetField(dataref,0,"MaxCornerAngle"));
+	FetchData(&bamgopts->maxnbv,mxGetField(dataref,0,"maxnbv"));
+	FetchData(&bamgopts->maxsubdiv,mxGetField(dataref,0,"maxsubdiv"));
+	FetchData(&bamgopts->Metrictype,mxGetField(dataref,0,"Metrictype"));
+	FetchData(&bamgopts->nbjacobi,mxGetField(dataref,0,"nbjacobi"));
+	FetchData(&bamgopts->nbsmooth,mxGetField(dataref,0,"nbsmooth"));
+	FetchData(&bamgopts->omega,mxGetField(dataref,0,"omega"));
+	FetchData(&bamgopts->power,mxGetField(dataref,0,"power"));
+	FetchData(&bamgopts->verbose,mxGetField(dataref,0,"verbose"));
+
+	FetchData(&bamgopts->Crack,mxGetField(dataref,0,"Crack"));
+	FetchData(&bamgopts->geometricalmetric,mxGetField(dataref,0,"geometricalmetric"));
+	FetchData(&bamgopts->KeepVertices,mxGetField(dataref,0,"KeepVertices"));
+	FetchData(&bamgopts->splitcorners,mxGetField(dataref,0,"splitcorners"));
+
+	FetchData(&bamgopts->hmin,mxGetField(dataref,0,"hmin"));
+	FetchData(&bamgopts->hmax,mxGetField(dataref,0,"hmax"));
+	FetchData(&bamgopts->hminVertices,&bamgopts->hminVerticesSize[0],&bamgopts->hminVerticesSize[1],mxGetField(dataref,0,"hminVertices"));
+	FetchData(&bamgopts->hmaxVertices,&bamgopts->hmaxVerticesSize[0],&bamgopts->hmaxVerticesSize[1],mxGetField(dataref,0,"hmaxVertices"));
+	FetchData(&bamgopts->hVertices,&bamgopts->hVerticesSize[0],&bamgopts->hVerticesSize[1],mxGetField(dataref,0,"hVertices"));
+	FetchData(&bamgopts->metric,&bamgopts->metricSize[0],&bamgopts->metricSize[1],mxGetField(dataref,0,"metric"));
+	FetchData(&bamgopts->field,&bamgopts->fieldSize[0],&bamgopts->fieldSize[1],mxGetField(dataref,0,"field"));
+	FetchData(&bamgopts->err,&bamgopts->errSize[0],&bamgopts->errSize[1],mxGetField(dataref,0,"err"));
+
+	/*Additional checks*/
+	bamgopts->Check();
+
+	/*Assign output pointers:*/
+	*pbamgopts=bamgopts;
+}
+/*}}}*/
+/*FUNCTION FetchData(Options** poptions,const mxArray** pdataref){{{*/
+void FetchData(Options** poptions,int istart, int nrhs,const mxArray** pdataref){
+
+	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 (!mxIsClass(pdataref[i],"char")) _error_("Argument " << i+1 << " must be name of option");
+
+		FetchData(&name,pdataref[i]);
+		if(i+1 == nrhs) _error_("Argument " << i+2 << " must exist and be value of option \"" << name << "\".");
+
+		option=(Option*)OptionParse(name,&pdataref[i+1]);
+		options->AddOption(option);
+		option=NULL;
+	}
+
+	/*Assign output pointers:*/
+	*poptions=options;
+}
+/*}}}*/
+/*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/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToDoubleMatrix.cpp	(revision 13975)
@@ -0,0 +1,130 @@
+/* \file MatlabMatrixToDoubleMatrix.cpp
+ * \brief: convert a sparse or dense matlab matrix to a double* pointer
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+/*Matlab includes: */
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int        i,j,count,rows,cols;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			/*Now, get ir,jc and pr: */
+			ir=mxGetIr(mxmatrix);
+			jc=mxGetJc(mxmatrix);
+
+			/*Now, start inserting data into double* matrix: */
+			count=0;
+			for(i=0;i<cols;i++){
+				for(j=0;j<(jc[i+1]-jc[i]);j++){
+					matrix[rows*ir[count]+i]=pmxmatrix[count];
+					count++;
+				}
+			}
+		}
+
+	}
+	else if(mxIsClass(mxmatrix,"double")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		double* pmxmatrix=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"single")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		float *pmxmatrix=(float*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"int16")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		short int *pmxmatrix=(short*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else if(mxIsClass(mxmatrix,"uint8")){
+		/*Dealing with dense matrix: recover pointer and size: */
+		char *pmxmatrix=(char*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*Create serial matrix: */
+		if(rows*cols){
+			matrix=xNewZeroInit<double>(rows*cols);
+
+			for(i=0;i<rows;i++){
+				for(j=0;j<cols;j++){
+					matrix[cols*i+j]=(double)pmxmatrix[rows*j+i];
+				}
+			}
+		}
+	}
+	else{
+		_error_("Matlab matrix type Not implemented yet");
+	}
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	*pmatrix_rows=rows;
+	*pmatrix_cols=cols;
+
+	return 1;
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToMatrix.cpp	(revision 13975)
@@ -0,0 +1,31 @@
+/*!\file MatlabMatrixToMatrix.cpp
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/toolkits/toolkits.h"
+
+Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix){
+
+	int dummy;
+	Matrix<double>* matrix=NULL;
+
+	/*allocate matrix object: */
+	matrix=new Matrix<double>();
+
+	#ifdef _HAVE_PETSC_
+	matrix->pmatrix=MatlabMatrixToPetscMat(mxmatrix);
+	#else
+	matrix->smatrix=MatlabMatrixToSeqMat(mxmatrix);
+	#endif
+
+	return matrix;
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToPetscMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToPetscMat.cpp	(revision 13975)
@@ -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 "../../c/shared/shared.h"
+
+/*Petsc includes: */
+#ifdef _HAVE_PETSC_
+#include <petscmat.h>
+#include <petscvec.h>
+#include <petscksp.h>
+#endif
+
+/*Matlab includes: */
+#include "./matlabio.h"
+
+PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix){
+
+	int dummy;
+	PetscMat* matrix=new PetscMat();
+
+	MatlabMatrixToPetscMat(&matrix->matrix, &dummy, &dummy, mxmatrix);
+
+	return matrix;
+}
+int MatlabMatrixToPetscMat(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){
+
+	int rows, cols;
+	double *mxmatrix_ptr = NULL;
+	double *tmatrix      = NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	Mat matrix = NULL;
+
+	/*matlab indices: */
+	mwIndex *ir = NULL;
+	mwIndex *jc = NULL;
+	double  *pr = NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*petsc indices: */
+	int *idxm = NULL;
+	int *idxn = NULL;
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		nnz=mxGetNzmax(mxmatrix);
+		if(rows){
+			nz=(int)((double)nnz/(double)rows);
+		}
+		else{
+			nz=0;
+		}
+
+		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);
+
+		/*Now, get ir,jc and pr: */
+		pr=mxGetPr(mxmatrix);
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+
+		/*Now, start inserting data into sparse matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
+				count++;
+			}
+		}
+	}
+	else{
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+
+		/*transpose, as Petsc now does not allows MAT_COLUMN_ORIENTED matrices in MatSetValues: */
+		tmatrix=xNew<double>(rows*cols);
+		for(i=0;i<cols;i++){
+			for(j=0;j<rows;j++){
+				*(tmatrix+rows*i+j)=*(mxmatrix_ptr+cols*j+i);
+			}
+		}
+
+		/*Create serial matrix: */
+		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);
+
+		/*Insert mxmatrix_ptr values into petsc matrix: */
+		idxm=xNew<int>(rows);
+		idxn=xNew<int>(cols);
+
+		for(i=0;i<rows;i++)idxm[i]=i;
+		for(i=0;i<cols;i++)idxn[i]=i;
+
+		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,tmatrix,INSERT_VALUES); CHKERRQ(ierr);
+
+		xDelete<double>(tmatrix);
+	}
+
+	/*Assemble matrix: */
+	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
+	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);
+
+	/*Assign output pointer: */
+	*pmatrix=matrix;
+	if(pmatrix_rows) *pmatrix_rows=rows;
+	if(pmatrix_cols) *pmatrix_cols=cols;
+
+	return 1;
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToSeqMat.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabMatrixToSeqMat.cpp	(revision 13975)
@@ -0,0 +1,25 @@
+/*!\file MatlabMatrixToSeqMat.cpp
+ */
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include "./matlabio.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/shared/shared.h"
+
+SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref){
+
+	SeqMat<double>* output=NULL;
+
+	output=new SeqMat<double>();
+	MatlabMatrixToDoubleMatrix(&output->matrix,&output->M,&output->N,dataref);
+	return output;
+
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabNArrayToNArray.cpp	(revision 13975)
@@ -0,0 +1,250 @@
+/* \file MatlabNArrayToNArray.cpp
+ * \brief: convert a sparse or dense matlab n-dimensional array to cpp n-dimensional array
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/include/include.h"
+
+/*FUNCTION MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	double* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	double* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	double  *pr    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel=mxGetNumberOfElements(mxmatrix);
+	ndims=mxGetNumberOfDimensions(mxmatrix);
+	ipt  =mxGetDimensions(mxmatrix);
+	size =xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+
+		matrix=xNewZeroInit<double>(rows*cols);
+
+		/*Now, get ir,jc and pr: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pr = mxGetPr(mxmatrix);
+
+		/*Now, start inserting data into double* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				*(matrix+rows*ir[count]+i)=pr[count];
+				count++;
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNewZeroInit<double>(numel);
+
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j = IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(double)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int  i,j,rows,cols;
+	int  numel,ndims;
+	int *size,*dims;
+	bool* mxmatrix_ptr=NULL;
+	const mwSize* ipt=NULL;
+
+	/*output: */
+	bool* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	bool    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows=mxGetM(mxmatrix);
+		cols=mxGetN(mxmatrix);
+		matrix=xNewZeroInit<bool>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir=mxGetIr(mxmatrix);
+		jc=mxGetJc(mxmatrix);
+		pm=(bool*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into bool* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=(bool*)mxGetData(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<bool>(numel);
+		dims=xNew<int>(ndims);
+		for(i=0;i<numel;i++){
+			ColumnWiseDimsFromIndex(dims,i,size,ndims);
+			j=IndexFromRowWiseDims(dims,size,ndims);
+			matrix[j]=(bool)mxmatrix_ptr[i];
+		}
+		xDelete<int>(dims);
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
+/*FUNCTION MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){{{*/
+int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix){
+
+	int           i,j,rows,cols;
+	int           numel,ndims;
+	int          *size , *dims;
+	mxChar       *mxmatrix_ptr = NULL;
+	const mwSize *ipt          = NULL;
+
+	/*output: */
+	char* matrix=NULL;
+
+	/*matlab indices: */
+	mwIndex *ir    = NULL;
+	mwIndex *jc    = NULL;
+	char    *pm    = NULL;
+	int      count;
+
+	/*get Matlab matrix information: */
+	numel = mxGetNumberOfElements(mxmatrix);
+	ndims = mxGetNumberOfDimensions(mxmatrix);
+	ipt   = mxGetDimensions(mxmatrix);
+	size  = xNew<int>(ndims);
+	for (i=0;i<ndims;i++) size[i]=(int)ipt[i];
+
+	/*Ok, first check if we are dealing with a sparse or full matrix: */
+	if (mxIsSparse(mxmatrix)){
+
+		/*Dealing with sparse matrix: recover size first: */
+		rows = mxGetM(mxmatrix);
+		cols = mxGetN(mxmatrix);
+		matrix=xNew<char>(rows*cols);
+
+		/*Now, get ir,jc and pm: */
+		ir = mxGetIr(mxmatrix);
+		jc = mxGetJc(mxmatrix);
+		pm = (char*)mxGetData(mxmatrix);
+
+		/*Now, start inserting data into char* matrix: */
+		count=0;
+		for(i=0;i<cols;i++){
+			for(j=0;j<(jc[i+1]-jc[i]);j++){
+				matrix[rows*ir[count]+i]=(char)pm[count];
+				count++;
+			}
+		}
+	}
+	else{
+		/*Dealing with dense matrix: recover pointer and size: */
+		mxmatrix_ptr=mxGetChars(mxmatrix);
+
+		/*Create serial matrix: */
+		matrix=xNew<char>(numel+1);
+		matrix[numel]='\0';
+
+		/*looping code adapted from Matlab example explore.c: */
+		int elements_per_page = size[0] * size[1];
+		/* total_number_of_pages = size[2] x size[3] x ... x size[N-1] */
+		int total_number_of_pages = 1;
+		for (i=2; i<ndims; i++) {
+			total_number_of_pages *= size[i];
+		}
+
+		i=0;
+		for (int page=0; page < total_number_of_pages; page++) {
+			int row;
+			/* On each page, walk through each row. */
+			for (row=0; row<size[0]; row++)  {
+				int column;
+				j = (page * elements_per_page) + row;
+
+				/* Walk along each column in the current row. */
+				for (column=0; column<size[1]; column++) {
+					*(matrix+i++)=(char)*(mxmatrix_ptr+j);
+					j += size[0];
+				}
+			}
+		}
+	}
+
+	/*Assign output pointer: */
+	*pmatrix       = matrix;
+	*pmatrix_numel = numel;
+	*pmatrix_ndims = ndims;
+	*pmatrix_size  = size;
+
+	return 1;
+}
+/*}}}*/
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToDoubleVector.cpp	(revision 13975)
@@ -0,0 +1,93 @@
+/* \file MatlabVectorToDoubleVector.cpp
+ * \brief: convert a sparse or dense matlab vector to a serial vector:
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <string.h>
+
+/*Matlab includes: */
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+
+int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector){
+
+	int rows,cols;
+	double* mxvector_ptr=NULL;
+	int ierr;
+	int i,j;
+
+	/*output: */
+	double* vector=NULL;
+
+	/*matlab indices: */
+	mwIndex*    ir=NULL;
+	mwIndex*    jc=NULL;
+	double* pr=NULL;
+	int     count;
+	int     nnz;
+	int     nz;
+
+	/*Ok, first check if we are dealing with a sparse or full vector: */
+	if (mxIsSparse(mxvector)){
+
+		/*Dealing with sparse vector: recover size first: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+		nnz=mxGetNzmax(mxvector);
+
+		/*Check that input is actualy a vector*/
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
+
+		nz=(int)((double)nnz/(double)rows);
+
+		if(rows){
+			vector=xNewZeroInit<double>(rows);
+
+			/*Now, get ir,jc and pr: */
+			pr=mxGetPr(mxvector);
+			ir=mxGetIr(mxvector);
+			jc=mxGetJc(mxvector);
+
+			/*Now, start inserting data into sparse vector: */
+			count=0;
+			for(i=0;i<cols;i++){
+				for(j=0;j<(jc[i+1]-jc[i]);j++){
+					vector[ir[count]]=pr[count];
+					count++;
+				}
+			}
+		}
+
+	}
+	else{
+
+		/*Dealing with dense vector: recover pointer and size: */
+		mxvector_ptr=(double*)mxGetPr(mxvector);
+		rows=mxGetM(mxvector);
+		cols=mxGetN(mxvector);
+
+		/*Check that input is actualy a vector*/
+		if (cols!=1) _error_("input vector of size " << rows << "x" << cols << " should have only one column");
+
+		/*allocate and memcpy*/
+		if(rows){
+			vector=xNew<double>(rows);
+			memcpy(vector,mxvector_ptr,rows*sizeof(double));
+		}
+		else{
+			vector=NULL;
+		}
+	}
+
+	/*Assign output pointer: */
+	*pvector=vector;
+	*pvector_rows=rows;
+
+	return 1;
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToPetscVec.cpp	(revision 13975)
@@ -0,0 +1,106 @@
+/* \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 "./matlabio.h"
+#include "../../c/shared/shared.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: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToSeqVec.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToSeqVec.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToSeqVec.cpp	(revision 13975)
@@ -0,0 +1,20 @@
+/*!\file MatlabVectorToSeqVec.cpp
+ */
+
+/*Headers:*/
+#include <mex.h>
+#include <stdio.h>
+#include <string.h>
+#include "./matlabio.h"
+#include "../../c/toolkits/toolkits.h"
+#include "../../c/shared/shared.h"
+
+SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref){
+
+	SeqVec<double>* output=NULL;
+
+	output=new SeqVec<double>();
+	MatlabVectorToDoubleVector(&output->vector,&output->M,dataref);
+	return output;
+
+}
Index: /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/MatlabVectorToVector.cpp	(revision 13975)
@@ -0,0 +1,31 @@
+/*!\file MatlabVectorToVector.cpp
+ */
+
+/*Headers:*/
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+#include <stdio.h>
+#include <string.h>
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/toolkits/toolkits.h"
+
+Vector<double>* MatlabVectorToVector(const mxArray* mxvector){
+
+	int dummy;
+	Vector<double>* vector=NULL;
+
+	/*allocate vector object: */
+	vector=new Vector<double>();
+
+	#ifdef _HAVE_PETSC_
+	vector->pvector=MatlabVectorToPetscVec(mxvector);
+	#else
+	vector->svector=MatlabVectorToSeqVec(mxvector);
+	#endif
+
+	return vector;
+}
Index: /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/OptionParse.cpp	(revision 13975)
@@ -0,0 +1,201 @@
+/*\file OptionParse.c
+ *\brief: functions to parse the mex options.
+ */
+#ifdef HAVE_CONFIG_H
+    #include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include <cstring> 
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+#include "../../c/io/io.h"
+
+GenericOption<double>* OptionDoubleParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+	FetchData(&odouble->value,prhs[0]);
+	odouble->numel=1;
+	odouble->ndims=1;
+	odouble->size=NULL;
+
+	return(odouble);
+}/*}}}*/
+GenericOption<double*>* OptionDoubleArrayParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<double*> *odouble = NULL;
+
+	/*check and parse the name  */
+	odouble=new GenericOption<double*>();
+	odouble->name =xNew<char>(strlen(name)+1);
+	memcpy(odouble->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"double")){
+		_error_("Value of option \"" << odouble->name  << "\" must be class \"double\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&odouble->value,&odouble->numel,&odouble->ndims,&odouble->size,prhs[0]);
+
+	return(odouble);
+}/*}}}*/
+GenericOption<bool*>* OptionLogicalParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<bool*> *ological = NULL;
+
+	/*check and parse the name  */
+	ological=new GenericOption<bool*>();
+	ological->name =xNew<char>(strlen(name)+1);
+	memcpy(ological->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"logical")){
+		_error_("Value of option \"" << ological->name  << "\" must be class \"logical\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ological->value,&ological->numel,&ological->ndims,&ological->size,prhs[0]);
+
+	return(ological);
+}/*}}}*/
+GenericOption<char*>* OptionCharParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	GenericOption<char*>  *ochar = NULL;
+
+	/*check and parse the name  */
+	ochar=new GenericOption<char*>();
+	ochar->name =xNew<char>(strlen(name)+1);
+	memcpy(ochar->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"char")){
+		_error_("Value of option \"" << ochar->name  << "\" must be class \"char\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	FetchData(&ochar->value,&ochar->numel,&ochar->ndims,&ochar->size,prhs[0]);
+
+	return(ochar);
+}/*}}}*/
+GenericOption<Options**>* OptionStructParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	char           namei[161];
+	Option*                   option      = NULL;
+	GenericOption<Options**>  *ostruct    = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *structi;
+	mwIndex        sindex;
+
+	/*check and parse the name  */
+	ostruct=new GenericOption<Options**>();
+	ostruct->name =xNew<char>(strlen(name)+1);
+	memcpy(ostruct->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"struct")){
+		_error_("Value of option \"" << ostruct->name  << "\" must be class \"struct\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+	ostruct->numel=mxGetNumberOfElements(prhs[0]);
+	ostruct->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt           =mxGetDimensions(prhs[0]);
+	ostruct->size =xNew<int>(ostruct->ndims);
+	for (i=0; i<ostruct->ndims; i++) ostruct->size[i]=(int)ipt[i];
+	if (ostruct->numel) ostruct->value=xNew<Options*>(ostruct->numel);
+
+	/*loop through and process each element of the struct array  */
+	for (sindex=0; sindex<ostruct->numel; sindex++) {
+		ostruct->value[sindex]=new Options;
+
+		/*loop through and process each field for the element  */
+		for (i=0; i<mxGetNumberOfFields(prhs[0]); i++) {
+			sprintf(namei,"%s.%s",name,mxGetFieldNameByNumber(prhs[0],i));
+			structi=mxGetFieldByNumber(prhs[0],sindex,i);
+
+			option=(Option*)OptionParse(namei,&structi);
+			ostruct->value[sindex]->AddObject((Object*)option);
+			option=NULL;
+		}
+	}
+
+	return(ostruct);
+}/*}}}*/
+GenericOption<Options*>* OptionCellParse( char* name, const mxArray* prhs[]){ /*{{{*/
+
+	int            i;
+	int           *dims;
+	char           namei[161];
+	char           cstr[81];
+	GenericOption<Options*> *ocell      = NULL;
+	Option        *option     = NULL;
+	const mwSize  *ipt        = NULL;
+	const mxArray *celli;
+	mwIndex        cindex;
+
+	/*check and parse the name  */
+	ocell=new GenericOption<Options*>();
+	ocell->name =xNew<char>(strlen(name)+1);
+	memcpy(ocell->name,name,(strlen(name)+1)*sizeof(char));
+
+	/*check and parse the value  */
+	if (!mxIsClass(prhs[0],"cell")){
+		_error_("Value of option \"" << ocell->name  << "\" must be class \"cell\", not class \"" << mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	ocell->numel=mxGetNumberOfElements(prhs[0]);
+	ocell->ndims=mxGetNumberOfDimensions(prhs[0]);
+	ipt         =mxGetDimensions(prhs[0]);
+	ocell->size =xNew<int>(ocell->ndims);
+	for (i=0; i<ocell->ndims; i++) ocell->size[i]=(int)ipt[i];
+	ocell->value=new Options;
+
+	/*loop through and process each element of the cell array  */
+	dims=xNew<int>(ocell->ndims);
+	for (cindex=0; cindex<ocell->numel; cindex++) {
+		ColumnWiseDimsFromIndex(dims,(int)cindex,ocell->size,ocell->ndims);
+		StringFromDims(cstr,dims,ocell->ndims);
+		#ifdef _INTEL_WIN_
+			_snprintf(namei,161,"%s%s",name,cstr);
+		#else
+			snprintf(namei,161,"%s%s",name,cstr);
+		#endif
+		celli=mxGetCell(prhs[0],cindex);
+
+		option=(Option*)OptionParse(namei,&celli);
+		ocell->value->AddObject((Object*)option);
+		option=NULL;
+	}
+	xDelete<int>(dims);
+
+	return(ocell);
+}/*}}}*/
+Option* OptionParse(char* name, const mxArray* prhs[]){ /*{{{*/
+
+	Option  *option = NULL;
+	mxArray *lhs[1];
+
+	/*parse the value according to the matlab data type  */
+	if     (mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])==1))
+	 option=(Option*)OptionDoubleParse(name,prhs);
+	else if(mxIsClass(prhs[0],"double")  && (mxGetNumberOfElements(prhs[0])!=1))
+	 option=(Option*)OptionDoubleArrayParse(name,prhs);
+	else if(mxIsClass(prhs[0],"logical"))
+	 option=(Option*)OptionLogicalParse(name,prhs);
+	else if(mxIsClass(prhs[0],"char"))
+	 option=(Option*)OptionCharParse(name,prhs);
+	else if(mxIsClass(prhs[0],"struct"))
+	 option=(Option*)OptionStructParse(name,prhs);
+	else if(mxIsClass(prhs[0],"cell"))
+	 option=(Option*)OptionCellParse(name,prhs);
+	else {
+		_pprintLine_("  Converting value of option \"" << name << "\" from unrecognized class \"" << mxGetClassName(prhs[0]) << "\" to class \"" << "struct" << "\".");
+		if (!mexCallMATLAB(1,lhs,1,(mxArray**)prhs,"struct")) {
+			option=(Option*)OptionStructParse(name,(const mxArray**)lhs);
+			mxDestroyArray(lhs[0]);
+		}
+		else _error_("Second argument value of option \""<< name <<"\" is of unrecognized class \""<< mxGetClassName(prhs[0]) <<"\".");
+	}
+
+	return(option);
+}/*}}}*/
Index: /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/WriteMatlabData.cpp	(revision 13975)
@@ -0,0 +1,388 @@
+/* \file WriteData.c:
+ * \brief: general interface for writing data
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#include "./matlabio.h"
+#include "../../c/shared/shared.h"
+
+/*Primitive data types*/
+/*FUNCTION WriteData(mxArray** pdataref,double* matrix, int M,int N){{{*/
+void WriteData(mxArray** pdataref,double* matrix, int M,int N){
+
+	mxArray *dataref  = NULL;
+	double  *tmatrix  = NULL;
+
+	if(matrix){
+		/*create the matlab matrixwith Matlab's memory manager */   
+		tmatrix=(double*)mxMalloc(M*N*sizeof(double));
+		for(int i=0;i<M;i++){
+			for(int j=0;j<N;j++){
+				tmatrix[j*M+i]=matrix[i*N+j];
+			}
+		}
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)N);
+		mxSetPr(dataref,(double*)tmatrix);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,int* matrix, int M,int N){{{*/
+void WriteData(mxArray** pdataref,int* matrix, int M,int N){
+
+	mxArray* dataref = NULL;
+	double*  tmatrix = NULL;
+
+	if(matrix){
+		/*convert to double matrix using Matlab's memory manager*/
+		double* tmatrix=(double*)mxMalloc(M*N*sizeof(double));
+		for(int i=0;i<M;i++){
+			for(int j=0;j<N;j++){
+				tmatrix[j*M+i]=(double)matrix[i*N+j];
+			}
+		}
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)N);
+		mxSetPr(dataref,(double*)tmatrix);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,double* vector, int M){{{*/
+void WriteData(mxArray** pdataref,double* vector, int M){
+
+	mxArray* dataref       = NULL;
+	double*  vector_matlab = NULL;
+
+	if(vector){
+
+		/*create the matlab vector with Matlab's memory manager */
+		vector_matlab=(double*)mxMalloc(M*sizeof(double));
+		for(int i=0;i<M;i++) vector_matlab[i]=vector[i];
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,(mwSize)M);
+		mxSetN(dataref,(mwSize)1);
+		mxSetPr(dataref,vector_matlab);
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,double scalar){{{*/
+void WriteData(mxArray** pdataref,double scalar){
+
+	*pdataref=mxCreateDoubleScalar(scalar);
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,int integer){{{*/
+void WriteData(mxArray** pdataref,int integer){
+
+		*pdataref=mxCreateDoubleScalar((double)integer);
+
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,int boolean){{{*/
+void WriteData(mxArray** pdataref,bool boolean){
+
+	*pdataref=mxCreateDoubleScalar((double)boolean);
+
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,char* string){{{*/
+void WriteData(mxArray** pdataref,char* string){
+
+		*pdataref=mxCreateString(string);
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref){{{*/
+void WriteData(mxArray** pdataref){
+
+		;
+
+}
+/*}}}*/
+
+/*ISSM objects*/
+/*FUNCTION WriteData(mxArray** pdataref,BamgGeom* bamggeom){{{*/
+void WriteData(mxArray** pdataref,BamgGeom* bamggeom){
+
+	/*Intermediary*/
+	int         i;
+	mxArray    *dataref           = NULL;
+	const int   numfields         = 8;
+	const char *fnames[numfields];
+	mwSize      ndim              = 2;
+	mwSize      dimensions[2]     = {1,1};
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "Vertices";
+	fnames[i++] = "Edges";
+	fnames[i++] = "TangentAtEdges";
+	fnames[i++] = "Corners";
+	fnames[i++] = "RequiredVertices";
+	fnames[i++] = "RequiredEdges";
+	fnames[i++] = "CrackedEdges";
+	fnames[i++] = "SubDomains";
+	_assert_(i==numfields);
+
+	/*Initialize Matlab structure*/
+	dataref=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	i=0;
+	i++; SetStructureField(dataref,"Vertices",        bamggeom->VerticesSize[0],        bamggeom->VerticesSize[1],        bamggeom->Vertices);
+	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);
+	i++; SetStructureField(dataref,"CrackedEdges",    bamggeom->CrackedEdgesSize[0],    bamggeom->CrackedEdgesSize[1],    bamggeom->CrackedEdges);
+	i++; SetStructureField(dataref,"SubDomains",      bamggeom->SubDomainsSize[0],      bamggeom->SubDomainsSize[1],      bamggeom->SubDomains);
+	_assert_(i==numfields);
+
+	/*Assign output*/
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,BamgMesh* bamgmesh){{{*/
+void WriteData(mxArray** pdataref,BamgMesh* bamgmesh){
+
+	/*Intermediary*/
+	int         i;
+	mxArray    *dataref           = NULL;
+	const int   numfields         = 16;
+	const char *fnames[numfields];
+	mwSize      ndim              = 2;
+	mwSize      dimensions[2]     = {1,1};
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "Vertices";
+	fnames[i++] = "Edges";
+	fnames[i++] = "Triangles";
+	fnames[i++] = "Quadrilaterals";
+	fnames[i++] = "IssmEdges";
+	fnames[i++] = "IssmSegments";
+	fnames[i++] = "VerticesOnGeomVertex";
+	fnames[i++] = "VerticesOnGeomEdge";
+	fnames[i++] = "EdgesOnGeomEdge";
+	fnames[i++] = "SubDomains";
+	fnames[i++] = "SubDomainsFromGeom";
+	fnames[i++] = "ElementConnectivity";
+	fnames[i++] = "NodalConnectivity";
+	fnames[i++] = "NodalElementConnectivity";
+	fnames[i++] = "CrackedVertices";
+	fnames[i++] = "CrackedEdges";
+	_assert_(i==numfields);
+
+	/*Initialize Matlab structure*/
+	dataref=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	i=0;
+	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,"VerticesOnGeomVertex",bamgmesh->VerticesOnGeomVertexSize[0],bamgmesh->VerticesOnGeomVertexSize[1], bamgmesh->VerticesOnGeomVertex);
+	i++; SetStructureField(dataref,"VerticesOnGeomEdge",bamgmesh->VerticesOnGeomEdgeSize[0],bamgmesh->VerticesOnGeomEdgeSize[1], bamgmesh->VerticesOnGeomEdge);
+	i++; SetStructureField(dataref,"EdgesOnGeomEdge", bamgmesh->EdgesOnGeomEdgeSize[0], bamgmesh->EdgesOnGeomEdgeSize[1],bamgmesh->EdgesOnGeomEdge);
+	i++; SetStructureField(dataref,"SubDomains",bamgmesh->SubDomainsSize[0], bamgmesh->SubDomainsSize[1],bamgmesh->SubDomains);
+	i++; SetStructureField(dataref,"SubDomainsFromGeom", bamgmesh->SubDomainsFromGeomSize[0], bamgmesh->SubDomainsFromGeomSize[1],bamgmesh->SubDomainsFromGeom);
+	i++; SetStructureField(dataref,"ElementConnectivity",bamgmesh->ElementConnectivitySize[0],bamgmesh->ElementConnectivitySize[1], bamgmesh->ElementConnectivity);
+	i++; SetStructureField(dataref,"NodalConnectivity",bamgmesh->NodalConnectivitySize[0],bamgmesh->NodalConnectivitySize[1], bamgmesh->NodalConnectivity);
+	i++; SetStructureField(dataref,"NodalElementConnectivity", bamgmesh->NodalElementConnectivitySize[0], bamgmesh->NodalElementConnectivitySize[1],bamgmesh->NodalElementConnectivity);
+	i++; SetStructureField(dataref,"CrackedVertices", bamgmesh->CrackedVerticesSize[0],bamgmesh->CrackedVerticesSize[1], bamgmesh->CrackedVertices);
+	i++; SetStructureField(dataref,"CrackedEdges",bamgmesh->CrackedEdgesSize[0], bamgmesh->CrackedEdgesSize[1],bamgmesh->CrackedEdges);
+	_assert_(i==numfields);
+
+	/*Assign output*/
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,SeqMat<double>* matrix){{{*/
+void WriteData(mxArray** pdataref,SeqMat<double>* matrix){
+
+	int      i,j;
+	int      rows,cols;
+	mxArray *dataref     = NULL;
+	double  *matrix_ptr  = NULL;
+	double  *tmatrix_ptr = NULL;
+
+	if(matrix){
+
+		matrix_ptr=matrix->ToSerial();
+		matrix->GetSize(&rows,&cols);
+
+		/*Now transpose the matrix and allocate with Matlab's memory manager: */
+		tmatrix_ptr=(double*)mxMalloc(rows*cols*sizeof(double));
+		for(i=0;i<rows;i++){
+			for(j=0;j<cols;j++){
+				tmatrix_ptr[j*rows+i]=matrix_ptr[i*cols+j];
+			}
+		}
+
+		/*create matlab matrix: */
+		dataref=mxCreateDoubleMatrix(0,0,mxREAL);
+		mxSetM(dataref,rows); 
+		mxSetN(dataref,cols);
+		mxSetPr(dataref,tmatrix_ptr);
+
+		/*Free ressources:*/
+		xDelete<double>(matrix_ptr);
+	}
+	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;
+	double*  vector_ptr=NULL;
+	double*  vector_matlab=NULL;
+	int      rows;
+
+	if(vector){
+		/*call toolkit routine: */
+		vector_ptr=vector->ToMPISerial();
+		vector->GetSize(&rows);
+
+		/*now create the matlab vector with Matlab's memory manager */
+		vector_matlab=(double*)mxMalloc(rows*sizeof(double));
+		for(int i=0;i<rows;i++) vector_matlab[i]=vector_ptr[i];
+
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);                         
+		mxSetM(dataref,rows);
+		mxSetN(dataref,1);                                                                                          
+		mxSetPr(dataref,vector_matlab);           
+	}
+	else{
+		dataref = mxCreateDoubleMatrix(0,0,mxREAL);
+	}
+
+	/*Clean-up and return*/
+	xDelete<double>(vector_ptr);
+	*pdataref=dataref;
+}
+/*}}}*/
+/*FUNCTION WriteData(mxArray** pdataref,RiftStruct* riftstruct){{{*/
+void WriteData(mxArray** pdataref,RiftStruct* riftstruct){
+
+	/*Intermediary*/
+	int         i;
+	mxArray    *dataref           = NULL;
+	const int   numfields         = 10;
+	const char *fnames[numfields];
+	mwSize      ndim              = 2;
+	mwSize      dimensions[2]     = {1,1};
+
+	/*Initialize field names*/
+	i=0;
+	fnames[i++] = "numsegs";
+	fnames[i++] = "segments";
+	fnames[i++] = "pairs";
+	fnames[i++] = "tips";
+	fnames[i++] = "penaltypairs";
+	fnames[i++] = "fill";
+	fnames[i++] = "friction";
+	fnames[i++] = "fraction";
+	fnames[i++] = "fractionincrement";
+	fnames[i++] = "state";
+	_assert_(i==numfields);
+
+	/*Initialize matlab structure of dimension numrifts*/
+	dimensions[0]=riftstruct->numrifts;
+	dataref=mxCreateStructArray(ndim,dimensions,numfields,fnames);
+
+	/*set each matlab each field*/
+	for(int i=0;i<riftstruct->numrifts;i++){
+		SetStructureFieldi(dataref,i,"numsegs"          ,riftstruct->riftsnumsegments[i]);
+		SetStructureFieldi(dataref,i,"segments"         ,riftstruct->riftsnumsegments[i]    ,3,riftstruct->riftssegments[i]);
+		SetStructureFieldi(dataref,i,"pairs"            ,riftstruct->riftsnumpairs[i]       ,2,riftstruct->riftspairs[i]);
+		SetStructureFieldi(dataref,i,"tips"             ,1                                  ,2,&riftstruct->riftstips[2*i]);
+		SetStructureFieldi(dataref,i,"penaltypairs"     ,riftstruct->riftsnumpenaltypairs[i],7,riftstruct->riftspenaltypairs[i]);
+		SetStructureFieldi(dataref,i,"fill"             ,IceEnum);
+		SetStructureFieldi(dataref,i,"friction"         ,0);
+		SetStructureFieldi(dataref,i,"fraction"         ,0.);
+		SetStructureFieldi(dataref,i,"fractionincrement",0.1);
+		SetStructureFieldi(dataref,i,"state"            ,riftstruct->riftsnumpenaltypairs[i],1,riftstruct->state[i]);
+	}
+
+	/*Assign output*/
+	*pdataref=dataref;
+}
+/*}}}*/
+
+/*Toolkit*/
+/*FUNCTION SetStructureField{{{*/
+void SetStructureField(mxArray* dataref,const char* fieldname,int M,int N,double* fieldpointer){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,fieldpointer,M,N);
+
+	/*Assign to structure*/
+	mxSetField(dataref,0,fieldname,field);
+}
+/*}}}*/
+/*FUNCTION SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int M,int N,double* fieldpointer){{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int M,int N,double* fieldpointer){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,fieldpointer,M,N);
+
+	/*Assign to structure*/
+	mxSetField(dataref,i,fieldname,field);
+}
+/*}}}*/
+/*FUNCTION SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int field){{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int fieldin){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,fieldin);
+
+	/*Assign to structure*/
+	mxSetField(dataref,i,fieldname,field);
+}
+/*}}}*/
+/*FUNCTION SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,double field){{{*/
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,double fieldin){
+
+	mxArray* field = NULL;
+
+	/*Convert field*/
+	WriteData(&field,fieldin);
+
+	/*Assign to structure*/
+	mxSetField(dataref,i,fieldname,field);
+}
+/*}}}*/
Index: /issm/trunk/src/wrappers/matlab/io/matlabio.h
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/matlabio.h	(revision 13975)
@@ -0,0 +1,93 @@
+/*\file matlabio.h
+ *\brief: I/O for ISSM in matlab mode
+ */
+
+#ifndef _MATLAB_IO_H_
+#define _MATLAB_IO_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include "../include/matlabincludes.h"
+#include "../../c/classes/classes.h"
+#include "../../c/Container/Container.h"
+#include "../../c/include/include.h"
+
+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,SeqVec<double>* vector);
+void WriteData(mxArray** pdataref,double* vector, int M);
+void WriteData(mxArray** pdataref,int integer);
+void WriteData(mxArray** pdataref,bool boolean);
+void WriteData(mxArray** pdataref,double scalar);
+void WriteData(mxArray** pdataref,char* string);
+void WriteData(mxArray** pdataref);
+void WriteData(mxArray** pdataref,BamgGeom* bamggeom);
+void WriteData(mxArray** pdataref,BamgMesh* bamgmesh);
+void WriteData(mxArray** pdataref,RiftStruct* riftstruct);
+
+void FetchData(double** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchData(double** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchData(int** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchData(bool** pmatrix,int* pM,int *pN,const mxArray* dataref);
+void FetchData(bool** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchData(Matrix<double>** pmatrix,const mxArray* dataref);
+void FetchData(int** pvector,int* pM,const mxArray* dataref);
+void FetchData(float** pvector,int* pM,const mxArray* dataref);
+void FetchData(double** pvector,int* pM,const mxArray* dataref);
+void FetchData(bool** pvector,int* pM,const mxArray* dataref);
+void FetchData(Vector<double>** pvector,const mxArray* dataref);
+void FetchData(char** pstring,const mxArray* dataref);
+void FetchData(char** pmatrix,int* pnumel,int* pndims,int** psize,const mxArray* dataref);
+void FetchData(double* pscalar,const mxArray* dataref);
+void FetchData(int* pinteger,const mxArray* dataref);
+void FetchData(bool* pbool,const mxArray* dataref);
+void FetchData(BamgGeom** bamggeom,const mxArray* dataref);
+void FetchData(BamgMesh** bamgmesh,const mxArray* dataref);
+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[]);
+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);
+void SetStructureField(mxArray* dataref,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int fieldrows,int fieldcols,double* fieldpointer);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,int field);
+void SetStructureFieldi(mxArray* dataref,int i,const char* fieldname,double field);
+int CheckNumMatlabArguments(int nlhs,int NLHS, int nrhs,int NRHS, const char* THISFUNCTION, void (*function)( void ));
+
+/*Matlab to Matrix routines: */
+Matrix<double>* MatlabMatrixToMatrix(const mxArray* mxmatrix);
+Vector<double>* MatlabVectorToVector(const mxArray* mxvector);
+
+/*Matlab to double* routines: */
+int MatlabVectorToDoubleVector(double** pvector,int* pvector_rows,const mxArray* mxvector);
+int MatlabMatrixToDoubleMatrix(double** pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix);
+int MatlabNArrayToNArray(double** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
+int MatlabNArrayToNArray(bool** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
+int MatlabNArrayToNArray(char** pmatrix,int* pmatrix_numel,int* pmatrix_ndims,int** pmatrix_size,const mxArray* mxmatrix);
+
+/*Matlab to SeqMat routines: */
+SeqMat<double>* MatlabMatrixToSeqMat(const mxArray* dataref);
+SeqVec<double>* MatlabVectorToSeqVec(const mxArray* dataref);
+
+/*Matlab to Petsc routines: */
+#ifdef _HAVE_PETSC_
+int MatlabMatrixToPetscMat(Mat* matrix,int* prows,int* pcols, const mxArray* mxmatrix);
+PetscMat* MatlabMatrixToPetscMat(const mxArray* mxmatrix);
+int MatlabVectorToPetscVec(Vec* pvector,int* pvector_rows,const mxArray* mxvector);
+PetscVec* MatlabVectorToPetscVec(const mxArray* mxvector);
+#endif
+
+#endif	/* _IO_H_ */
Index: /issm/trunk/src/wrappers/matlab/io/mxGetAssignedField.cpp
===================================================================
--- /issm/trunk/src/wrappers/matlab/io/mxGetAssignedField.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/matlab/io/mxGetAssignedField.cpp	(revision 13975)
@@ -0,0 +1,39 @@
+/*!\file: mxGetAssignedField.c: 
+ * \brief: abstract interface on parallel side for i/o, so it ressembles the serial i/o.
+ *
+ * In serial mode, this routine takes care of returning the field coming 
+ * from the model. If largesize is 1, we are running out of core models in 
+ * matlab, and we need to call the subsref private method from the model object
+ * in order to correctly load the data from disk.
+ */
+
+#include "./matlabio.h"
+
+mxArray* mxGetAssignedField(const mxArray* pmxa_array,int number,const char* field){
+
+	//output
+	mxArray* mxfield=NULL;
+
+	//input
+	mxArray    *inputs[2];
+	mxArray    *pindex      = NULL;
+	const char *fnames[2];
+	mwSize      ndim        = 2;
+	mwSize      onebyone[2] = {1,1};
+
+	//We want to call the subsasgn method, and get the returned array.This ensures that if we are running 
+	//large sized problems, the data is truly loaded from disk by the model subsasgn class method.
+	inputs[0]=(mxArray*)pmxa_array; //this is the model
+
+	//create index structure used in the assignment (index.type='.' and index.subs='x' for field x for ex)
+	fnames[0] = "type";
+	fnames[1] = "subs";
+	pindex=mxCreateStructArray( ndim,onebyone,2,fnames);
+	mxSetField( pindex, 0, "type",mxCreateString("."));
+	mxSetField( pindex, 0, "subs",mxCreateString(field));
+	inputs[1]=pindex;
+
+	mexCallMATLAB( 1, &mxfield, 2, (mxArray**)inputs, "subsref");
+
+	return mxfield;
+}
Index: /issm/trunk/src/wrappers/python/Makefile.am
===================================================================
--- /issm/trunk/src/wrappers/python/Makefile.am	(revision 13975)
+++ /issm/trunk/src/wrappers/python/Makefile.am	(revision 13975)
@@ -0,0 +1,139 @@
+AM_CPPFLAGS = @DAKOTAINCL@ @PETSCINCL@ @MPIINCL@ @SPOOLESINCL@ @METISINCL@ @TRIANGLEINCL@ @CHACOINCL@ @SCOTCHINCL@ @SHAPELIBINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
+
+EXEEXT=$(PYTHONWRAPPEREXT)
+
+#python io{{{
+lib_LIBRARIES = libISSMPython.a 
+if SHAREDLIBS
+lib_LTLIBRARIES = libISSMPython.la
+else
+	lib_LTLIBRARIES =
+endif
+
+io_sources= ./include/pythonincludes.h\
+				./io/pythonio.h\
+				./io/WritePythonData.cpp\
+				./io/CheckNumPythonArguments.cpp\
+				./io/FetchPythonData.cpp
+
+ALLCXXFLAGS= -fPIC -D_GNU_SOURCE -fno-omit-frame-pointer -pthread -D_CPP_  -D_WRAPPERS_ $(CXXFLAGS) $(CXXOPTFLAGS) 
+libISSMPython_a_SOURCES = $(io_sources)
+libISSMPython_a_CXXFLAGS= $(ALLCXXFLAGS)
+if SHAREDLIBS
+libISSMPython_la_SOURCES = $(io_sources)
+endif
+#}}}
+#Wrappers {{{
+if WRAPPERS
+lib_LTLIBRARIES = BamgConvertMesh.la\
+						BamgMesher.la\
+						ContourToMesh.la\
+						ContourToNodes.la\
+						ElementConnectivity.la\
+						EnumToString.la\
+						InterpFromMeshToMesh2d.la\
+						InterpFromGridToMesh.la\
+						MeshProfileIntersection.la\
+						NodeConnectivity.la\
+						StringToEnum.la\
+						TriMesh.la\
+						TriMeshProcessRifts.la
+endif 
+#}}}
+#Flags and libraries {{{
+#if SHAREDLIBS
+#deps = ../../c/libISSMCore.la ../../c/libISSMModules.la
+#else
+#deps = ../../c/libISSMCore.a ../../c/libISSMModules.a
+#endif
+#deps +=  $(MATHLIB) ${PYTHONLIB}
+deps =  $(MATHLIB) ${PYTHONLIB}
+
+#Triangle library
+AM_CXXFLAGS =  -DTRILIBRARY -DANSI_DECLARATORS -DNO_TIMER -D_WRAPPERS_
+
+#Python part
+AM_LDFLAGS   = $(PYTHONLINK) -shrext ${EXEEXT} -module
+if VERSION
+AM_LDFLAGS +=
+else
+AM_LDFLAGS += -avoid-version
+endif
+if SHAREDLIBS
+deps += ./libISSMPython.la 
+else
+deps += ./libISSMPython.a
+AM_LDFLAGS += --no-warnings 
+endif
+
+AM_CXXFLAGS +=  -D_HAVE_PYTHON_MODULES_   -fPIC
+if PYTHON3
+AM_CXXFLAGS +=  -DNPY_NO_DEPRECATED_API 
+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 {{{
+BamgConvertMesh_la_SOURCES = ../BamgConvertMesh/BamgConvertMesh.cpp\
+									  ../BamgConvertMesh/BamgConvertMesh.h
+BamgConvertMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+BamgMesher_la_SOURCES = ../BamgMesher/BamgMesher.cpp\
+								../BamgMesher/BamgMesher.h
+BamgMesher_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+ContourToMesh_la_SOURCES = ../ContourToMesh/ContourToMesh.cpp\
+									 ../ContourToMesh/ContourToMesh.h
+ContourToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+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)
+
+InterpFromGridToMesh_la_SOURCES = ../InterpFromGridToMesh/InterpFromGridToMesh.cpp\
+												../InterpFromGridToMesh/InterpFromGridToMesh.h
+InterpFromGridToMesh_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB) $(MULTITHREADINGLIB)
+
+MeshProfileIntersection_la_SOURCES = ../MeshProfileIntersection/MeshProfileIntersection.cpp\
+										../MeshProfileIntersection/MeshProfileIntersection.h
+MeshProfileIntersection_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+NodeConnectivity_la_SOURCES = ../NodeConnectivity/NodeConnectivity.cpp\
+										../NodeConnectivity/NodeConnectivity.h
+NodeConnectivity_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+
+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)
+
+TriMeshProcessRifts_la_SOURCES = ../TriMeshProcessRifts/TriMeshProcessRifts.cpp\
+											../TriMeshProcessRifts/TriMeshProcessRifts.h
+TriMeshProcessRifts_la_LIBADD = ${deps} $(MPILIB) $(PETSCLIB)
+#}}}
Index: /issm/trunk/src/wrappers/python/include/pythonincludes.h
===================================================================
--- /issm/trunk/src/wrappers/python/include/pythonincludes.h	(revision 13975)
+++ /issm/trunk/src/wrappers/python/include/pythonincludes.h	(revision 13975)
@@ -0,0 +1,24 @@
+
+#ifndef _PYTHON_INCLUDES_H_
+#define _PYTHON_INCLUDES_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_PYTHON_
+
+#if _PYTHON_MAJOR_ == 2
+#undef NPY_NO_DEPRECATED_API
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#else
+#define NPY_NO_DEPRECATED_API 
+#endif
+
+#include <Python.h>
+#include <arrayobject.h>
+
+#endif
+#endif /*_PYTHON_INCLUDES_H_*/
Index: /issm/trunk/src/wrappers/python/include/wrapper_macros.h
===================================================================
--- /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 13975)
+++ /issm/trunk/src/wrappers/python/include/wrapper_macros.h	(revision 13975)
@@ -0,0 +1,92 @@
+/* \file python_macros.h
+ * \brief: macros used for the python bindings
+ */
+
+#ifndef _PY_WRAPPER_MACROS_H_
+#define _PY_WRAPPER_MACROS_H_
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#ifdef _HAVE_PYTHON_
+/* MODULEBOOT/MODULEEND {{{*/
+
+/*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*/
+#define MODULEBOOT(); \
+	PyObject *output = PyTuple_New(NLHS); \
+	int       nrhs   = (int)PyTuple_Size(args);  \
+	if(!output) return NULL;\
+	try{ \
+	IssmComm::SetComm(-1);
+
+#define MODULEEND(); }\
+  catch(ErrorException &exception){\
+	  PyErr_SetString(PyExc_TypeError,exception.PythonReport()); \
+	  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
+/* WRAPPER 3.2 {{{*/
+#define WRAPPER(modulename,...)  \
+\
+static PyObject* modulename(PyObject* self,PyObject* args);\
+static PyMethodDef modulename##_funcs[] = {\
+	{#modulename, (PyCFunction)modulename, METH_VARARGS, ""},\
+	{NULL,NULL,0,NULL}\
+};\
+\
+static struct PyModuleDef modulename##module= {\
+	PyModuleDef_HEAD_INIT,\
+	#modulename,   /* name of module */\
+	NULL, /* module documentation, may be NULL */\
+	-1,       /* size of per-interpreter state of the module,\
+				 or -1 if the module keeps state in global variables. */\
+	modulename##_funcs\
+};\
+\
+PyMODINIT_FUNC PyInit_##modulename(void){\
+\
+	import_array();\
+	return PyModule_Create(&modulename##module);\
+}\
+\
+static PyObject* modulename(PyObject* self,PyObject* args)
+/*}}}*/
+#else
+/* WRAPPER 2.7 {{{*/
+#define WRAPPER(modulename,...)  \
+\
+static PyObject* modulename(PyObject* self,PyObject* args);\
+static PyMethodDef modulename##_funcs[] = {\
+	{#modulename, (PyCFunction)modulename, METH_VARARGS, ""},\
+	{NULL,NULL,0,NULL}\
+};\
+\
+PyMODINIT_FUNC init##modulename(void){\
+\
+	import_array();\
+	(void) Py_InitModule(#modulename, modulename##_funcs);\
+}\
+\
+static PyObject* modulename(PyObject* self,PyObject* args)
+/*}}}*/
+#endif
+/* CHECKARGUMENTS {{{*/
+#define CHECKARGUMENTS(NLHS,NRHS,functionpointer) CheckNumPythonArguments(args, NRHS,functionpointer)
+/*}}}*/
+#endif
+#endif
Index: /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/python/io/CheckNumPythonArguments.cpp	(revision 13975)
@@ -0,0 +1,29 @@
+/*!\file CheckNumPythonArguments.cpp:
+ * \brief: check number of arguments and report an usage error message.
+ */
+
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#define NO_IMPORT
+
+#include "./pythonio.h"
+#include "../../c/shared/Exceptions/exceptions.h"
+#include "../../c/include/include.h"
+
+int CheckNumPythonArguments(PyObject* inputs,int NRHS, void (*function)( void )){
+
+	Py_ssize_t size=0;
+
+	/*figure out size of tuple in input: */
+	size=PyTuple_Size(inputs);
+
+	/*check on requested size: */
+	if (size==0){
+		function();
+		_error_("usage: see above");
+	}
+	else if (size!=NRHS ) {
+		function(); 
+		_error_("usage error.");
+	}
+	return 1;
+}
Index: /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/python/io/FetchPythonData.cpp	(revision 13975)
@@ -0,0 +1,354 @@
+/*\file FetchData.cpp:
+ * \brief: general I/O interface to fetch data in python
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#define NO_IMPORT
+
+#include "./pythonio.h"
+#include "../../c/include/include.h"
+#include "../../c/shared/shared.h"
+
+/*Primitive data types*/
+/*FUNCTION FetchData(double* pscalar,PyObject* py_float){{{*/
+void FetchData(double* pscalar,PyObject* py_float){
+
+	double scalar;
+
+	/*return internal value: */
+	scalar=PyFloat_AsDouble(py_float);
+
+	/*output: */
+	*pscalar=scalar;
+}
+/*}}}*/
+/*FUNCTION FetchData(int* pinteger,PyObject* py_long){{{*/
+void FetchData(int* pinteger, PyObject* py_long){
+
+	int integer;
+
+	/*return internal value: */
+	integer=(int)PyLong_AsLong(py_long);
+
+	/*output: */
+	*pinteger=integer;
+}
+/*}}}*/
+/*FUNCTION FetchData(bool* pboolean,PyObject* py_boolean){{{*/
+void FetchData(bool* pboolean,PyObject* py_boolean){
+
+	bool boolean;
+
+	/*check this is indeed a subtype of long type: */
+	if(!PyBool_Check(py_boolean))_error_("expecting a boolean in input!");
+
+	/*extract boolean: */
+	boolean=(bool)PyLong_AsLong(py_boolean);
+
+	/*simple copy: */
+	*pboolean=boolean;
+
+}
+/*}}}*/
+/*FUNCTION FetchData(double** pmatrix,int* pM, int* pN, PyObject* py_matrix){{{*/
+void FetchData(double** pmatrix,int* pM,int *pN,PyObject* py_matrix){
+
+	/*output: */
+	double* dmatrix=NULL;
+	double* matrix=NULL;
+	int M,N;
+	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];
+
+	if (M && N) {
+		/*retrieve internal value: */
+		dmatrix=(double*)PyArray_DATA((PyArrayObject*)py_matrix);
+
+		/*copy matrix: */
+		matrix=xNew<double>(M*N);
+		memcpy(matrix,dmatrix,(M*N)*sizeof(double));
+	}
+	else
+		matrix=NULL;
+
+	/*output: */
+	if(pM)*pM=M;
+	if(pN)*pN=N;
+	if(pmatrix)*pmatrix=matrix;
+}
+/*}}}*/
+/*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];
+
+	if (M && N) {
+		/*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];
+	}
+	else
+		matrix=NULL;
+
+	/*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;
+	int ndim;
+	npy_intp*  dims=NULL;
+
+	/*retrive dimensions: */
+	ndim=PyArray_NDIM((const PyArrayObject*)py_vector);
+	if(ndim!=1)_error_("expecting an Mx1 vector in input!");
+	dims=PyArray_DIMS((PyArrayObject*)py_vector);
+	M=dims[0]; 
+
+	if (M) {
+		/*retrieve internal value: */
+		dvector=(double*)PyArray_DATA((PyArrayObject*)py_vector);
+
+		/*copy vector: */
+		vector=xNew<double>(M);
+		memcpy(vector,dvector,(M)*sizeof(double));
+	}
+	else
+		vector=NULL;
+
+	/*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;
+}
+/*}}}*/
+
+/*Python version dependent: */
+#if _PYTHON_MAJOR_ >= 3 
+/*FUNCTION FetchData(char** pstring,PyObject* py_unicode){{{*/
+void FetchData(char** pstring,PyObject* py_unicode){
+
+	PyObject* py_bytes;
+	char* string=NULL;
+
+	/*convert to bytes format: */
+	PyUnicode_FSConverter(py_unicode,&py_bytes);
+
+	/*convert from bytes to string: */
+	string=PyBytes_AS_STRING(py_bytes);
+
+	*pstring=string;
+}
+/*}}}*/
+#else
+/*FUNCTION FetchData(char** pstring,PyObject* py_string){{{*/
+void FetchData(char** pstring,PyObject* py_string){
+
+	char* string=NULL;
+
+	/*extract internal string: */
+	string=PyString_AsString(py_string);
+
+	/*copy string (note strlen does not include trailing NULL): */
+	*pstring=xNew<char>(strlen(string)+1);
+	memcpy(*pstring,string,(strlen(string)+1)*sizeof(char));
+}
+/*}}}*/
+#endif
Index: /issm/trunk/src/wrappers/python/io/WritePythonData.cpp
===================================================================
--- /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 13975)
+++ /issm/trunk/src/wrappers/python/io/WritePythonData.cpp	(revision 13975)
@@ -0,0 +1,194 @@
+/* \file WriteData.c:
+ * \brief: general interface for writing data
+ */
+
+#ifdef HAVE_CONFIG_H
+	#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif
+
+#define PY_ARRAY_UNIQUE_SYMBOL PythonIOSymbol
+#define NO_IMPORT
+
+#include "./pythonio.h"
+#include "../../c/include/include.h"
+#include "../../c/Container/Container.h"
+#include "../../c/shared/shared.h"
+#include "../../c/EnumDefinitions/EnumDefinitions.h"
+
+/*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((Py_ssize_t)integer));
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,char* string){{{*/
+void WriteData(PyObject* py_tuple, int index, char* string){
+
+	PyTuple_SetItem(py_tuple, index, PyUnicode_FromString(string));
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* 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);
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index){{{*/
+void WriteData(PyObject* py_tuple, int index){
+
+	PyTuple_SetItem(py_tuple, index, Py_None);
+
+}/*}}}*/
+
+/*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 WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){{{*/
+void WriteData(PyObject* py_tuple,int index,SeqMat<double>* matrix){
+
+	int M,N;
+	double* buffer=NULL;
+	npy_intp dims[2]={0,0};
+	PyObject* array=NULL;
+
+	buffer=matrix->ToSerial();
+	matrix->GetSize(&M,&N);
+	dims[0]=(npy_intp)M;
+	dims[1]=(npy_intp)N;
+	array=PyArray_SimpleNewFromData(2,dims,NPY_DOUBLE,buffer);
+
+	PyTuple_SetItem(py_tuple, index, array);
+
+}/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,SeqVec<double>* vector){{{*/
+void WriteData(PyObject* py_tuple,int index,SeqVec<double>* vector){
+
+	int M;
+	double* buffer=NULL;
+	npy_intp dim=10;
+	PyObject* array=NULL;
+
+	buffer=vector->ToMPISerial();
+	vector->GetSize(&M);
+	dim=(npy_intp)M;
+	array=PyArray_SimpleNewFromData(1,&dim,NPY_DOUBLE,buffer);
+
+	PyTuple_SetItem(py_tuple, index, array);
+}
+/*}}}*/
+/*FUNCTION WriteData(PyObject* py_tuple,int index,RiftStruct* riftstruct){{{*/
+void WriteData(PyObject* py_tuple,int index,RiftStruct* riftstruct){
+
+	int i;
+	PyObject* list=NULL;
+	PyObject* dict=NULL;
+
+	list=PyList_New((Py_ssize_t)0);
+
+	for (i=0; i<riftstruct->numrifts; i++) {
+		dict=PyDict_New();
+
+		PyDict_SetItemString(dict,"numsegs"          ,PyInt_FromSsize_t((Py_ssize_t)riftstruct->riftsnumsegments[i]));
+		PyDict_SetItemString(dict,"segments"         ,PyArrayFromCopiedData(riftstruct->riftsnumsegments[i]    ,3,riftstruct->riftssegments[i]));
+		PyDict_SetItemString(dict,"pairs"            ,PyArrayFromCopiedData(riftstruct->riftsnumpairs[i]       ,2,riftstruct->riftspairs[i]));
+		PyDict_SetItemString(dict,"tips"             ,PyArrayFromCopiedData(1                                  ,2,&riftstruct->riftstips[2*i]));
+		PyDict_SetItemString(dict,"penaltypairs"     ,PyArrayFromCopiedData(riftstruct->riftsnumpenaltypairs[i],7,riftstruct->riftspenaltypairs[i]));
+		PyDict_SetItemString(dict,"fill"             ,PyInt_FromSsize_t((Py_ssize_t)IceEnum));
+		PyDict_SetItemString(dict,"friction"         ,PyInt_FromSsize_t((Py_ssize_t)0));
+		PyDict_SetItemString(dict,"fraction"         ,PyFloat_FromDouble(0.));
+		PyDict_SetItemString(dict,"fractionincrement",PyFloat_FromDouble(0.1));
+		PyDict_SetItemString(dict,"state"            ,PyArrayFromCopiedData(riftstruct->riftsnumpenaltypairs[i],1,riftstruct->state[i]));
+
+		PyList_Append(list, dict);
+	}
+
+	PyTuple_SetItem(py_tuple, index, list);
+}
+/*}}}*/
+
+/*Utils*/
+/*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 PyArrayFromCopiedData(int dimi,int dimj,double* data){{{*/
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,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)dimi;
+	pydims[1]=(npy_intp)dimj;
+	pydata=xNew<IssmDouble>(dimi*dimj);
+	memcpy(pydata,data,dimi*dimj*sizeof(double));
+	return PyArray_SimpleNewFromData(2,pydims,NPY_DOUBLE,pydata);
+}
+/*}}}*/
Index: /issm/trunk/src/wrappers/python/io/pythonio.h
===================================================================
--- /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 13975)
+++ /issm/trunk/src/wrappers/python/io/pythonio.h	(revision 13975)
@@ -0,0 +1,48 @@
+/*\file pythonio.h
+ *\brief: I/O for ISSM in python mode
+ */
+
+#ifndef _PYTHON_IO_H_
+#define _PYTHON_IO_H_
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#else
+#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
+#endif 
+
+#include "../include/pythonincludes.h"
+#include "../../c/classes/classes.h"
+#include "../../c/Container/Container.h"
+#include "../../c/include/include.h"
+
+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);
+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,int index, RiftStruct* riftstruct);
+
+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 ));
+
+/*Utils*/
+PyObject* PyArrayFromCopiedData(int dims[2],double* data);
+PyObject* PyArrayFromCopiedData(int dimi,int dimj,double* data);
+
+#endif	/* _IO_H_ */
Index: /issm/trunk/startup.py
===================================================================
--- /issm/trunk/startup.py	(revision 13974)
+++ /issm/trunk/startup.py	(revision 13975)
@@ -16,20 +16,5 @@
 	raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!')
 
-#Now add all issm code paths necessary to run issm smoothly. 
-#We capture the error output, so that we can warn the user to update 
-#the variable ISSM_DIR in this file, in case it is not correctly setup. 
-
-#ISSM path. Go through src/py and load everything we find  that looks like a python file
-for root,dirs,files in os.walk(ISSM_DIR+ '/src/py'):
-	if '.svn' in dirs:
-		dirs.remove('.svn')
-	for file in files:
-		if file.find(".py") != -1:
-			if file.find(".pyc") == -1:
-				#add to path 
-				sys.path.append(root)
-				file=os.path.splitext(file)[0]
-				#__import__(file)
-
+#Go through src/m and append any directory that contains a *.py file to PATH 
 for root,dirs,files in os.walk(ISSM_DIR+ '/src/m'):
 	if '.svn' in dirs:
@@ -38,52 +23,8 @@
 		if file.find(".py") != -1:
 			if file.find(".pyc") == -1:
-				#add to path 
-				sys.path.append(root)
-				file=os.path.splitext(file)[0]
-				#__import__(file)
+				if root not in sys.path:
+					sys.path.append(root)
 				
 sys.path.append(ISSM_DIR + '/lib')
 
-#Deal with scipy import: 
-import scipy 
-import numpy
-import nose
-
-#Import modules that are absolutely needed in ISSM {{{
-from model import *
-from mesh import *
-from mask import *
-from geometry import *
-from constants import *
-from surfaceforcings import *
-from basalforcings import *
-from matice import *
-from friction import *
-from flowequation import *
-from fielddisplay import *
-from timestepping import *
-from initialization import *
-from rifts import *
-from debug import *
-from settings import *
-from solver import *
-from ismumps  import * 
-from pairoptions  import * 
-from petscversion  import * 
-from asmoptions import *           
-from iluasmoptions import *        
-from jacobiasmoptions import *     
-from jacobicgoptions import *      
-from matlaboptions import *        
-from mumpsoptions import *         
-from soroptions import *           
-from stokesoptions import *
-from generic import *
-from hydrology import *
-from miscellaneous import *
-from private import *
-from triangle import *
-from setmask import *
-#}}}
-
 print("\n  To get started with ISSM, type issmdoc at the command prompt.\n\n")
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1301.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1301.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1301.py	(revision 13975)
@@ -0,0 +1,87 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1301.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+#  This file can be run to check that the melting in simple conduction is correctly modeled.
+
+#  There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
+
+#  at upper surface and an impose flux at its base. The result must be a linear temperature from the upper to the lower
+
+#  surface with an imposed slope (Geothermal flux). if it is not the case, something is thermal modeling has been changed...
+
+printingflag=false
+
+
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareThermal.py')
+md.extrude(3,2.)
+md=setflowequation(md,'Pattyn','all')
+
+
+# Some conditions specific to melting test
+
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1)
+md.initialization.temperature=273.15*ones(md.mesh.numberofvertices,1)
+pos=numpy.nonzero(md.mesh.vertexonsurface)
+md.thermal.spctemperature(pos)=md.initialization.temperature(pos)
+md.materials.rheology_B=paterson(md.initialization.temperature)
+
+
+# analytical results
+
+# melting heat = geothermal flux
+
+# Mb*L*rho=G   => Mb=G/L*rho
+
+melting=md.basalforcings.geothermalflux/(md.materials.rho_ice*md.materials.latentheat)*md.constants.yts
+
+
+# modeled  results
+
+md.cluster=generic('name',oshostname(),'np',2)
+md=solve(md,ThermalSolutionEnum())
+
+
+# plot results
+
+comp_melting=md.results.ThermalSolution.BasalforcingsMeltingRate
+relative=abs((comp_melting-melting)./melting)*100
+relative(find(comp_melting==melting))=0
+plotmodel()(md,'data',comp_melting,'title','Modeled melting','data',melting,'title','Analytical melting',\
+	'data',comp_melting-melting,'title','Absolute error','data',relative,'title','Relative error [%]',\
+	'layer#all',1,'caxis#2',[1.02964 1.02966]*10^-4,'FontSize#all',20,'figposition','mathieu')
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel()('thermalmelting','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off')
+	system(['mv thermalmelting.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Thermal '])
+end
+
+
+
+
+# Fields and tolerances to track changes
+
+field_names     =['BasalMelting']
+field_tolerances=[1e-08]
+field_values    =[comp_melting]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1302.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1302.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1302.py	(revision 13975)
@@ -0,0 +1,86 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1302.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+#  This file can be run to check that the advection-diffusion  is correctly modeled.
+
+#  There is u=v=0 and w=cst everywhere the only thermal boundary conditions are an imposed temperature
+
+#  at upper surface and an impose flux at its base.
+
+printingflag=false
+
+
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareThermal.py')
+md.extrude(30,1.)   %NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%.)
+md=setflowequation(md,'Pattyn','all') 
+
+
+# Thermal boundary conditions
+
+pos1=numpy.nonzero(md.mesh.elementonbed)     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10
+pos2=numpy.nonzero(md.mesh.elementonsurface) md.thermal.spctemperature(md.mesh.elements(pos2,4:6))=0
+md.initialization.vz=0.1*ones(md.mesh.numberofvertices,1)
+md.initialization.vel=sqrt( md.initialization.vx.^2+ md.initialization.vy.^2+ md.initialization.vz.^2)
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1)
+
+
+md.thermal.stabilization=2
+# analytical results
+
+# d2T/dz2-w*rho_ice*c/k*dT/dz=0   T(surface)=0  T(bed)=10   => T=A exp(alpha z)+B
+
+alpha=0.1/md.constants.yts*md.materials.rho_ice*md.materials.heatcapacity/md.materials.thermalconductivity   %alpha=w rho_ice c /k  and w=0.1m/an
+A=10/(exp(alpha*(-1000))-1)    %A=T(bed)/(exp(alpha*bed)-1)  with bed=-1000 T(bed)=10
+B=-A
+md.initialization.temperature=A*exp(alpha*md.mesh.z)+B
+
+
+# modeled  results
+
+md.cluster=generic('name',oshostname(),'np',2)
+md=solve(md,ThermalSolutionEnum())
+
+
+# plot results
+
+comp_temp=md.results.ThermalSolution.Temperature
+relative=abs((comp_temp-md.initialization.temperature)./md.initialization.temperature)*100
+relative(find(comp_temp==md.initialization.temperature))=0
+plotmodel()(md,'data',comp_temp,'title','Modeled temperature [K]','data',md.initialization.temperature,'view',3,\
+	'title','Analytical temperature [K]','view',3,'data',comp_temp-md.initialization.temperature,\
+	'title','Absolute error [K]','view',3,'data',relative,'title','Relative error [%]','view',3,\
+	'figposition','mathieu','FontSize#all',20)
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel()('thermaladvection','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off')
+	system(['mv thermaladvection.png ' ISSM_DIR '/website/doc_pdf/validation/Images/EISMINT '])
+end
+
+
+# Fields and tolerances to track changes
+
+field_names     =['AdvectionTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1303.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1303.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1303.py	(revision 13975)
@@ -0,0 +1,80 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1303.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+#  This file can be run to check that the conduction is correctly modeled.
+
+#  There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
+
+#  at the lower and upper surface. The result must be a linear temperature from the upper to the lower
+
+#  surface. if it is not the case, something is thermal modeling has been changed...
+
+printingflag=false
+
+
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareThermal.py')
+md.extrude(11,2.)
+md=setflowequation(md,'Pattyn','all')
+pos1=numpy.nonzero(md.mesh.elementonbed)     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10
+pos2=numpy.nonzero(md.mesh.elementonsurface) md.thermal.spctemperature(md.mesh.elements(pos2,4:6))=0
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1)
+
+
+# analytical results
+
+# d2T/dz2=0 T(bed)=10 T(surface)=0  => T=0*(z-bed)/thickness+10*(surface-z)/thickness
+
+# each layer of the 3d mesh must have a constant value
+
+md.initialization.temperature=10*(md.geometry.surface-md.mesh.z)./md.geometry.thickness
+
+
+# modeled  results
+
+md.cluster=generic('name',oshostname(),'np',2)
+md=solve(md,ThermalSolutionEnum())
+
+
+# plot results
+
+comp_temp=md.results.ThermalSolution.Temperature
+relative=abs((comp_temp-md.initialization.temperature)./md.initialization.temperature)*100
+relative(find(comp_temp==md.initialization.temperature))=0
+plotmodel()(md,'data',comp_temp,'title','Modeled temperature [K]','data',md.initialization.temperature,'view',3,\
+	'title','Analytical temperature [K]','view',3,'data',comp_temp-md.initialization.temperature,\
+	'title','Absolute error [K]','view',3,'data',relative,'title','Relative error [%]','view',3,\
+	'figposition','mathieu','FontSize#all',20)
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel()('thermalconduction','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off')
+	system(['mv thermalconduction.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Thermal '])
+end
+
+
+# Fields and tolerances to track changes
+
+field_names     =['ConductionTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1304.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1304.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1304.py	(revision 13975)
@@ -0,0 +1,82 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1304.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+#  This file can be run to check that the geothermal flux in simple conduction is correctly modeled.
+
+#  There is no velocity (no advection) the only thermal boundary conditions are an imposed temperature
+
+#  at upper surface and an impose flux at its base. The result must be a linear temperature from the upper to the lower
+
+#  surface with an imposed slope (Geothermal flux). if it is not the case, something is thermal modeling has been changed...
+
+printingflag=false
+
+
+md=model()
+md=triangle(md,'../Exp/Square.exp',100000)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareThermal.py')
+md.extrude(11,1.)
+md=setflowequation(md,'Pattyn','all')
+
+
+pos2=numpy.nonzero(md.mesh.elementonsurface) md.thermal.spctemperature(md.mesh.elements(pos2,4:6))=0
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1)
+md.basalforcings.geothermalflux(:)=0.1 %100mW/m^2
+
+
+# analytical results
+
+# the result is linear with depth and is equal to 0 on the upper surface (See BC)
+
+# d2T/dz2=0  -k*dT/dz(bed)=G  T(surface)=0  => T=-G/k*(z-surface)
+
+md.initialization.temperature=-0.1/md.materials.thermalconductivity*(md.mesh.z-md.geometry.surface) %G=0.1 W/m2
+
+
+# modeled  results
+
+md.cluster=generic('name',oshostname(),'np',2)
+md=solve(md,ThermalSolutionEnum())
+
+
+# plot results
+
+comp_temp=md.results.ThermalSolution.Temperature
+relative=abs((comp_temp-md.initialization.temperature)./md.initialization.temperature)*100
+relative(find(comp_temp==md.initialization.temperature))=0
+plotmodel()(md,'data',comp_temp,'title','Modeled temperature [K]','data',md.initialization.temperature,'view',3,\
+	'title','Analytical temperature','view',3,'data',comp_temp-md.initialization.temperature,\
+	'title','Absolute error [K]','view',3,'data',relative,'title','Relative error [%]','view',3,\
+	'figposition','mathieu','FontSize#all',20)
+if printingflag, 
+	set(gcf,'Color','w')
+	printmodel()('thermalgeothermalflux','png','margin','on','marginsize',25,'frame','off','resolution',0.7,'hardcopy','off')
+	system(['mv thermalgeothermalflux.png ' ISSM_DIR '/website/doc_pdf/validation/Images/Thermal '])
+end
+
+
+# Fields and tolerances to track changes
+
+field_names     =['GeothermalFluxTemperature']
+field_tolerances=[1e-13]
+field_values    =[comp_temp]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1501.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1501.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1501.py	(revision 13975)
@@ -0,0 +1,267 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1501.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+printingflag = false
+
+
+md=triangle(model(),'../Exp/Square.exp',350000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.transient.isthermal=0
+
+
+md.timestepping.time_step=1
+md.settings.output_frequency=1
+md.timestepping.final_time=2000
+
+
+# Solve for thinning rate -> -1 * surface mass balance
+
+smb= 2*ones(md.mesh.numberofvertices,1)   
+md.surfaceforcings.mass_balance= smb
+md.basalforcings.melting_rate= smb
+
+
+md=solve(md,PrognosticSolutionEnum())
+
+
+for i=1:10
+	 md=solve(md,PrognosticSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - (md.results['PrognosticSolution'][1]['Thickness']-md.geometry.thickness)
+end
+
+
+# Set up transient
+
+smb = md.surfaceforcings.mass_balance
+
+
+tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ]
+smb=[ [ones(399,1)*(smb')]' smb  tooth tooth]
+
+
+md.surfaceforcings.mass_balance= smb
+md.surfaceforcings.mass_balance(end+1,:)=[1:2000]
+
+
+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', \
+	'Vx5','Vy5','Vel5','Pressure5','Bed5','Surface5','Thickness5','SurfaceforcingsMassBalance5']
+field_tolerances=[1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10,\
+	1e-09,1e-09,1e-09,1e-10,1e-10,1e-10,1e-10,1e-10]
+field_values=[\
+	md.results['TransientSolution'][400]['Vx'],\
+	md.results['TransientSolution'][400]['Vy'],\
+	md.results['TransientSolution'][400]['Vel'],\
+	md.results['TransientSolution'][400]['Pressure'],\
+	md.results['TransientSolution'][400]['Bed'],\
+	md.results['TransientSolution'][400]['Surface'],\
+	md.results['TransientSolution'][400]['Thickness'],\
+	md.results['TransientSolution'][400]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][800]['Vx'],\
+	md.results['TransientSolution'][800]['Vy'],\
+	md.results['TransientSolution'][800]['Vel'],\
+	md.results['TransientSolution'][800]['Pressure'],\
+	md.results['TransientSolution'][800]['Bed'],\
+	md.results['TransientSolution'][800]['Surface'],\
+	md.results['TransientSolution'][800]['Thickness'],\
+	md.results['TransientSolution'][800]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][1200]['Vx'],\
+	md.results['TransientSolution'][1200]['Vy'],\
+	md.results['TransientSolution'][1200]['Vel'],\
+	md.results['TransientSolution'][1200]['Pressure'],\
+	md.results['TransientSolution'][1200]['Bed'],\
+	md.results['TransientSolution'][1200]['Surface'],\
+	md.results['TransientSolution'][1200]['Thickness'],\
+	md.results['TransientSolution'][1200]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][1600]['Vx'],\
+	md.results['TransientSolution'][1600]['Vy'],\
+	md.results['TransientSolution'][1600]['Vel'],\
+	md.results['TransientSolution'][1600]['Pressure'],\
+	md.results['TransientSolution'][1600]['Bed'],\
+	md.results['TransientSolution'][1600]['Surface'],\
+	md.results['TransientSolution'][1600]['Thickness'],\
+	md.results['TransientSolution'][1600]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][2000]['Vx'],\
+	md.results['TransientSolution'][2000]['Vy'],\
+	md.results['TransientSolution'][2000]['Vel'],\
+	md.results['TransientSolution'][2000]['Pressure'],\
+	md.results['TransientSolution'][2000]['Bed'],\
+	md.results['TransientSolution'][2000]['Surface'],\
+	md.results['TransientSolution'][2000]['Thickness'],\
+	md.results['TransientSolution'][2000]['SurfaceforcingsMassBalance'],\
+	]
+
+
+if printingflag,
+
+
+	starttime = 360
+	endtime = 2000
+	res = 40
+	ts = [starttime:res:endtime]
+
+
+	index = md.mesh.elements
+	x1=md.mesh.x(index(:,1)) x2=md.mesh.x(index(:,2)) x3=md.mesh.x(index(:,3))
+	y1=md.mesh.y(index(:,1)) y2=md.mesh.y(index(:,2)) y3=md.mesh.y(index(:,3))
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)))
+
+
+	thickness = []
+	volume = []
+	massbal = []
+	velocity = []
+	for t=starttime:endtime
+		thickness = [thickness md.results['TransientSolution'][t]['Thickness']]
+		volume = [volume meanmd.results['TransientSolution'][t]['Thicknessvalue,2'].*areas]
+		massbal = [massbal md.results['TransientSolution'][t]['SurfaceforcingsMassBalance']]
+		velocity = [velocity md.results['TransientSolution'][t]['Vel']]
+	end
+
+
+	figure('Position', [0 0 860 932])
+
+
+	options = plotoptions('data','transient_movie','unit','km')
+	options = options.list[1]
+	options = checkplotoptions(md,options)
+
+
+# 	loop over the time steps
+
+	results=md.results.TransientSolution
+	count = 1
+	for i=ts
+
+
+		subplot(5,9,[28:31 37:40])
+		set(gca,'pos',get(gca,'pos')+[-0.08 -0.08 0.07 0.08])
+		field = 'Thickness'
+
+
+# 		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)
+		options=changefieldvalue(options,'title',titlestring)
+		options=addfielddefault(options,'colorbar',1)
+		options=changefieldvalue(options,'caxis',[0 max(max(thickness))])
+		applyoptions(md,[],options)
+
+
+		subplot(5,9,[33:36 42:45])
+		set(gca,'pos',get(gca,'pos')+[-0.00 -0.08 0.07 0.08])
+		field = 'Vel'
+
+
+# 		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)
+		options=changefieldvalue(options,'title',titlestring)
+		options=addfielddefault(options,'colorbar',1)
+		options=changefieldvalue(options,'caxis',[0 max(max(velocity))])
+		applyoptions(md,[],options)
+
+
+		subplot(5,4,1:4)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0.03 0.12 0.015])
+		plot(starttime:endtime,mean(massbal),'k','LineWidth', 4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Surface Mass Balance','FontSize',14)
+		ylabel('m/year','FontSize',14)
+
+
+		subplot(5,4,5:8)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0.015 0.12 0.015])
+		plot(starttime:endtime,sum(volume)/1000/1000/1000,'LineWidth',4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Ice Volume','FontSize',14)
+		ylabel('km^3','FontSize',14)
+
+
+		subplot(5,4,9:12)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0 0.12 0.015])
+		plot(starttime:endtime,mean(velocity)/1000, 'LineWidth', 4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Mean Velocity','FontSize', 14)
+		ylabel('km/year','FontSize', 14)
+		xlabel('year','FontSize', 14)
+
+
+		set(gcf,'Renderer','zbuffer','color','white') %fixes a bug on Mac OS X (not needed in future Matlab version)
+		if i==starttime,
+# 			initialize images and frame
+
+			frame=getframe(gcf)
+			[images,map]=rgb2ind(frame.cdata,256,'nodither')
+			images(1,1,1,length(ts))=0
+		else
+			frame=getframe(gcf)
+			images(:,:,1,count) = rgb2ind(frame.cdata,map,'nodither')
+		end
+
+
+		count = count+1
+
+
+	end
+
+
+	filename='transawtooth2d.gif'
+	imwrite(images,map,filename,'DelayTime',1.0,'LoopCount',inf)
+
+
+end %printingflag
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1502.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1502.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1502.py	(revision 13975)
@@ -0,0 +1,273 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1502.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+printingflag = false
+
+
+md=triangle(model(),'../Exp/Square.exp',450000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.extrude(3,1.)
+md.cluster=generic('name',oshostname(),'np',2)
+md.transient.isthermal=0
+
+
+md.timestepping.time_step=1
+md.settings.output_frequency=1
+md.timestepping.final_time=2000
+
+
+# Solve for thinning rate -> -1 * surface mass balance
+
+smb= 2*ones(md.mesh.numberofvertices,1)   
+md.surfaceforcings.mass_balance= smb
+md.basalforcings.melting_rate= smb
+
+
+md=solve(md,PrognosticSolutionEnum())
+
+
+for i=1:10
+	 md=solve(md,PrognosticSolutionEnum())
+	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - (md.results['PrognosticSolution'][1]['Thickness']-md.geometry.thickness)
+end
+
+
+# Set up transient
+
+smb = md.surfaceforcings.mass_balance
+
+
+tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ]
+smb=[ [ones(399,1)*(smb')]' smb  tooth tooth]
+
+
+md.surfaceforcings.mass_balance= smb
+md.surfaceforcings.mass_balance(end+1,:)=[1:2000]
+
+
+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','SurfaceforcingsMassBalance4', \
+	'Vx5','Vy5','Vz5','Vel5','Pressure5','Bed5','Surface5','Thickness5','SurfaceforcingsMassBalance5']
+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,\
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13]
+field_values=[\
+	md.results['TransientSolution'][400]['Vx'],\
+	md.results['TransientSolution'][400]['Vy'],\
+	md.results['TransientSolution'][400]['Vz'],\
+	md.results['TransientSolution'][400]['Vel'],\
+	md.results['TransientSolution'][400]['Pressure'],\
+	md.results['TransientSolution'][400]['Bed'],\
+	md.results['TransientSolution'][400]['Surface'],\
+	md.results['TransientSolution'][400]['Thickness'],\
+	md.results['TransientSolution'][400]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][800]['Vx'],\
+	md.results['TransientSolution'][800]['Vy'],\
+	md.results['TransientSolution'][800]['Vz'],\
+	md.results['TransientSolution'][800]['Vel'],\
+	md.results['TransientSolution'][800]['Pressure'],\
+	md.results['TransientSolution'][800]['Bed'],\
+	md.results['TransientSolution'][800]['Surface'],\
+	md.results['TransientSolution'][800]['Thickness'],\
+	md.results['TransientSolution'][800]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][1200]['Vx'],\
+	md.results['TransientSolution'][1200]['Vy'],\
+	md.results['TransientSolution'][1200]['Vz'],\
+	md.results['TransientSolution'][1200]['Vel'],\
+	md.results['TransientSolution'][1200]['Pressure'],\
+	md.results['TransientSolution'][1200]['Bed'],\
+	md.results['TransientSolution'][1200]['Surface'],\
+	md.results['TransientSolution'][1200]['Thickness'],\
+	md.results['TransientSolution'][1200]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][1600]['Vx'],\
+	md.results['TransientSolution'][1600]['Vy'],\
+	md.results['TransientSolution'][1600]['Vz'],\
+	md.results['TransientSolution'][1600]['Vel'],\
+	md.results['TransientSolution'][1600]['Pressure'],\
+	md.results['TransientSolution'][1600]['Bed'],\
+	md.results['TransientSolution'][1600]['Surface'],\
+	md.results['TransientSolution'][1600]['Thickness'],\
+	md.results['TransientSolution'][1600]['SurfaceforcingsMassBalance'],\
+	md.results['TransientSolution'][2000]['Vx'],\
+	md.results['TransientSolution'][2000]['Vy'],\
+	md.results['TransientSolution'][2000]['Vz'],\
+	md.results['TransientSolution'][2000]['Vel'],\
+	md.results['TransientSolution'][2000]['Pressure'],\
+	md.results['TransientSolution'][2000]['Bed'],\
+	md.results['TransientSolution'][2000]['Surface'],\
+	md.results['TransientSolution'][2000]['Thickness'],\
+	md.results['TransientSolution'][2000]['SurfaceforcingsMassBalance'],\
+	]
+
+
+if printingflag,
+
+
+	starttime = 360
+	endtime = 2000
+	res = 40
+	ts = [starttime:res:endtime]
+
+
+	index = md.mesh.elements
+	x1=md.mesh.x(index(:,1)) x2=md.mesh.x(index(:,2)) x3=md.mesh.x(index(:,3))
+	y1=md.mesh.y(index(:,1)) y2=md.mesh.y(index(:,2)) y3=md.mesh.y(index(:,3))
+	areas=(0.5*((x2-x1).*(y3-y1)-(y2-y1).*(x3-x1)))
+
+
+	thickness = []
+	volume = []
+	massbal = []
+	velocity = []
+	for t=starttime:endtime
+		thickness = [thickness md.results['TransientSolution'][t]['Thickness']]
+		volume = [volume meanmd.results['TransientSolution'][t]['Thicknessvalue,2'].*areas]
+		massbal = [massbal md.results['TransientSolution'][t]['SurfaceforcingsMassBalance']]
+		velocity = [velocity md.results['TransientSolution'][t]['Vel']]
+	end
+
+
+	figure('Position', [0 0 1060 1060])
+
+
+	options = plotoptions('data','transient_movie','unit','km')
+	options = options.list[1]
+	options = checkplotoptions(md,options)
+
+
+# 	loop over the time steps
+
+	results=md.results.TransientSolution
+	count = 1
+	for i=ts
+
+
+		subplot(5,9,[28:31 37:40])
+		set(gca,'pos',get(gca,'pos')+[-0.08 -0.08 0.07 0.08])
+		field = 'Thickness'
+
+
+# 		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)
+		options=changefieldvalue(options,'title',titlestring)
+		options=addfielddefault(options,'colorbar',1)
+		options=changefieldvalue(options,'caxis',[0 max(max(thickness))])
+		applyoptions(md,[],options)
+
+
+		subplot(5,9,[33:36 42:45])
+		set(gca,'pos',get(gca,'pos')+[-0.01 -0.08 0.07 0.08])
+		field = 'Vel'
+
+
+# 		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)
+		options=changefieldvalue(options,'title',titlestring)
+		options=addfielddefault(options,'colorbar',1)
+		options=changefieldvalue(options,'caxis',[0 max(max(velocity))])
+		applyoptions(md,[],options)
+
+
+		subplot(5,4,1:4)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0.03 0.12 0.015])
+		plot(starttime:endtime,mean(massbal),'k','LineWidth', 4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Surface Mass Balance','FontSize',14)
+		ylabel('m/year','FontSize',14)
+
+
+		subplot(5,4,5:8)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0.015 0.12 0.015])
+		plot(starttime:endtime,sum(volume)/1000/1000/1000,'LineWidth',4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Ice Volume','FontSize',14)
+		ylabel('km^3','FontSize',14)
+
+
+		subplot(5,4,9:12)
+		cla
+		set(gca,'pos',get(gca,'pos')+[-0.07 0 0.12 0.015])
+		plot(starttime:endtime,mean(velocity)/1000, 'LineWidth', 4)
+		hold on
+		ya = ylim
+		plot([i i], ya, 'r', 'LineWidth',6)
+		ylim(ya) xlim([starttime endtime])
+		title('Mean Velocity','FontSize', 14)
+		ylabel('km/year','FontSize', 14)
+		xlabel('year','FontSize', 14)
+
+
+		set(gcf,'Renderer','zbuffer','color','white') %fixes a bug on Mac OS X (not needed in future Matlab version)
+		if i==starttime,
+# 			initialize images and frame
+
+			frame=getframe(gcf)
+			[images,map]=rgb2ind(frame.cdata,256,'nodither')
+			images(1,1,1,length(ts))=0
+		else
+			frame=getframe(gcf)
+			images(:,:,1,count) = rgb2ind(frame.cdata,map,'nodither')
+		end
+
+
+		count = count+1
+
+
+	end
+
+
+	filename='transawtooth3d.gif'
+	imwrite(images,map,filename,'DelayTime',1.0,'LoopCount',inf)
+
+
+end %printingflag
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1601.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1601.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1601.py	(revision 13975)
@@ -0,0 +1,76 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1601.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.diagnostic.spcvx(numpy.nonzero(md.mesh.y>0))=NaN
+md.initialization.vx(:)=0
+md.initialization.vy(:)=0
+md.initialization.vel(:)=0
+
+
+md.cluster=generic('name',oshostname,'np',2)
+md=solve(md,DiagnosticSolutionEnum())
+vel0=md.results.DiagnosticSolution.Vel
+
+
+theta=30*pi/180
+x=md.mesh.x
+y=md.mesh.y
+md.mesh.x=cos(theta)*x-sin(theta)*y
+md.mesh.y=sin(theta)*x+cos(theta)*y
+
+
+md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1)
+md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1)
+md=solve(md,DiagnosticSolutionEnum())
+vel1=md.results.DiagnosticSolution.Vel
+
+
+plotmodel()(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel1))/(max(abs(vel0))+eps)) ])
+
+
+# Now, put CS back to normal except on the side where the spc are applied
+
+pos=find(x==0 | x==1000000)
+md.diagnostic.referential(:)=NaN
+md.diagnostic.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1)
+md.diagnostic.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1)
+md=solve(md,DiagnosticSolutionEnum())
+vel2=md.results.DiagnosticSolution.Vel
+
+
+plotmodel()(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel2))/(max(abs(vel0))+eps)) ])
+
+
+# Fields and tolerances to track changes
+
+field_names     =['vel1','vel2']
+field_tolerances=[1e-11,1e-11]
+field_values=[\
+	vel1, \
+	vel2, \
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1602.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1602.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test1602.py	(revision 13975)
@@ -0,0 +1,62 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test1602.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'pattyn','all')
+md.diagnostic.spcvx(numpy.nonzero(md.mesh.y>0))=NaN
+md.initialization.vx(:)=0
+md.initialization.vy(:)=0
+md.initialization.vel(:)=0
+
+
+md.cluster=generic('name',oshostname,'np',3)
+md=solve(md,DiagnosticSolutionEnum())
+vel0=md.results.DiagnosticSolution.Vel
+
+
+theta=30*pi/180
+x=md.mesh.x
+y=md.mesh.y
+md.mesh.x=cos(theta)*x-sin(theta)*y
+md.mesh.y=sin(theta)*x+cos(theta)*y
+
+
+md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1)
+md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1)
+md=solve(md,DiagnosticSolutionEnum())
+vel1=md.results.DiagnosticSolution.Vel
+
+
+plotmodel()(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
+disp(['Error between Cartesian and rotated CS: ' num2str(max(abs(vel0-vel1))/(max(abs(vel0))+eps)) ])
+
+
+# Fields and tolerances to track changes
+
+field_names     =['vel1']
+field_tolerances=[1e-9]
+field_values=[\
+	vel1, \
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test218.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test218.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test218.py	(revision 13975)
@@ -0,0 +1,152 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test218.m
+Created on 2012-09-27 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=squaremesh(model(),1000000,1000000,5,5)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+
+# redo the parameter file for this special shelf. 
+
+# constant thickness, constrained (vy=0) flow into an icefront, 
+
+# from 0 m/yr at the grounding line.
+
+
+
+# needed later
+
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+xmin=min(md.mesh.x)
+xmax=max(md.mesh.x)
+
+
+di=md.materials.rho_ice/md.materials.rho_water
+
+
+h=1000
+md.geometry.thickness=h*ones(md.mesh.numberofvertices,1)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+
+# Initial velocity and pressure
+
+md.initialization.vx=zeros(md.mesh.numberofvertices,1)
+md.initialization.vy=zeros(md.mesh.numberofvertices,1)
+md.initialization.vz=zeros(md.mesh.numberofvertices,1)
+md.initialization.pressure=zeros(md.mesh.numberofvertices,1)
+
+
+# Materials
+
+md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1)
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3*ones(md.mesh.numberofelements,1)
+
+
+# Boundary conditions:
+
+md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1)
+md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1)
+md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1)
+
+
+# constrain flanks to 0 normal velocity
+
+pos=numpy.nonzero(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=numpy.nonzero(md.mesh.y==ymin)
+md.diagnostic.spcvx(pos)=0
+md.diagnostic.spcvy(pos)=0
+
+
+# icefront
+
+nodeonicefront=zeros(md.mesh.numberofvertices,1)
+pos=numpy.nonzero(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.pytition=md.qmu.pytition-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.pyams.direct=true
+md.qmu.pyams.analysis_driver='diagnostic'
+md.qmu.pyams.evaluation_concurrency=1
+md.qmu.pyams.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.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.dakota.importancefactors,\
+]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3001.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3001.py	(revision 13975)
@@ -0,0 +1,47 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3001.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve 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.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'][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/InNeedOfDebugging/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3002.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3002.py	(revision 13975)
@@ -0,0 +1,43 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3002.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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'][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/InNeedOfDebugging/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3003.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3003.py	(revision 13975)
@@ -0,0 +1,52 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3003.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'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.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'][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/InNeedOfDebugging/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3004.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3004.py	(revision 13975)
@@ -0,0 +1,43 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3004.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md.extrude(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'][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/InNeedOfDebugging/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3005.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3005.py	(revision 13975)
@@ -0,0 +1,38 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3005.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3006.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3006.py	(revision 13975)
@@ -0,0 +1,42 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3006.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve 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.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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3007.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3007.py	(revision 13975)
@@ -0,0 +1,39 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3007.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.extrude(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'][1]['Thickness'],\
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3008.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3008.py	(revision 13975)
@@ -0,0 +1,41 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3008.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'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.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'][1]['Temperature'],\
+	md.results['ThermalSolution'][1]['BasalforcingsMeltingRate'],\
+	]
Index: /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3009.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3009.py	(revision 13975)
@@ -0,0 +1,44 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3009.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'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.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/InNeedOfDebugging/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3010.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/InNeedOfDebugging/test3010.py	(revision 13975)
@@ -0,0 +1,66 @@
+"""
+== == == == == == == == == == == == == == == == == == ==
+Auto generated python script for ISSM:   test3010.m
+Created on 2012-09-25 via translateToPy.py Ver 1.0 by mikep
+== == == == == == == == == == == == == == == == == == ==
+
+Matlab script conversion into python
+translateToPy.py Author: Michael Pellegrin
+translateToPy.py Date: 09/24/12
+== == == == == == == == == == == == == == == == == == ==
+"""
+
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+import numpy
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'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.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/ad.m
===================================================================
--- /issm/trunk/test/NightlyRun/ad.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/ad.m	(revision 13975)
@@ -1,26 +1,30 @@
-md=triangle(model,'../Exp/Square.exp',50000);
+md=triangle(model(),'../Exp/Square.exp',100000.);
 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);
+md.verbose.autodiff=true;
+md.autodiff.independents={...
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices);
+	%independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fov_forward_indices',(1:md.mesh.numberofvertices)')
+	%independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',1)
+	};
 
-%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),...
+md.autodiff.dependents={...
+	dependent('name','MaxVel','type','scalar','fos_reverse_index',1)...
+	%dependent('name','IceVolume','type','scalar')...
+	%dependent('name','MassFlux','type','scalar','exp','../Exp/MassFlux1.exp','mesh',md.mesh,'index',1)...
+	%dependent('name','MassFlux','type','scalar','exp','../Exp/MassFlux2.exp','mesh',md.mesh,'index',2)...
 	};
+
+%md.autodiff.driver='fos_forward';
+md.autodiff.driver='fos_reverse';
+
+md=solve(md,TransientSolutionEnum());
+
+%plot
+nods=md.mesh.numberofvertices;
+jac=md.results.TransientSolution(1).AutodiffJacobian;
+plotmodel(md,'data',jac(1:nods),'data',jac(nods+1:2*nods),'data',jac(2*nods+1:3*nods),'data',jac(3*nods+1:4*nods));
Index: /issm/trunk/test/NightlyRun/ad_maxalloc.m
===================================================================
--- /issm/trunk/test/NightlyRun/ad_maxalloc.m	(revision 13975)
+++ /issm/trunk/test/NightlyRun/ad_maxalloc.m	(revision 13975)
@@ -0,0 +1,19 @@
+md=triangle(model(),'../Exp/Square.exp',100000.);
+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.verbose.autodiff=true;
+md.autodiff.independents={...
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fov_forward_indices',(1:md.mesh.numberofvertices)')
+	};
+
+md.autodiff.dependents={...
+	dependent('name','MaxVel','type','scalar')
+	};
+
+md.autodiff.driver='fov_forward';
+
+md=solve(md,TransientSolutionEnum());
Index: /issm/trunk/test/NightlyRun/python_skipped_tests.txt
===================================================================
--- /issm/trunk/test/NightlyRun/python_skipped_tests.txt	(revision 13975)
+++ /issm/trunk/test/NightlyRun/python_skipped_tests.txt	(revision 13975)
@@ -0,0 +1,12 @@
+%Get full list with:
+%  for i in test*.m; do NAME=$(echo $i | sed -e "s/\.m//"); %if [ ! -f $NAME.py ]; then echo $NAME; fi; done
+
+test218    needs Dakota
+test234    needs Dakota
+test235    needs Dakota
+test412    needs Dakota
+test413    needs Dakota
+test414    needs Dakota
+test417    needs Dakota
+test418    needs Dakota
+test420    needs Dakota
Index: /issm/trunk/test/NightlyRun/python_test_guidelines.txt
===================================================================
--- /issm/trunk/test/NightlyRun/python_test_guidelines.txt	(revision 13975)
+++ /issm/trunk/test/NightlyRun/python_test_guidelines.txt	(revision 13975)
@@ -0,0 +1,12 @@
+Guidelines for language-independent tests (as much as possible!):
+
+- Functions (e.g., model() and Enum()) have argument lists, even if blank.  Add the parentheses to distinguish them from variables.
+- Floating points numbers should have decimal points.  Expressions without decimals (e.g. 2/7) can evaluate incorrectly.
+- Make indentation consistent in appearance as well as content (e.g., don't mix tabs and equivalent number of spaces).
+- Separate statements on separate lines are more general.
+- Be careful with vectors vs. column arrays (unfortunately Matlab does not distinguish).  Documentation (like in the class def) showing whether more than one column is possible is very helpful.
+- Be careful with variable names that might be reserved words in other languages (e.g. "list").
+- Weird shortcuts for a particular language are not very general.
+- Since some languages are base 0 and some are base 1, it would be nice to name variables to clearly delineate which are indices and which are ID's (e.g., indices into node/element arrays vs. node/element ID's).  
+- Checks like isnan(array) may be ambiguous, depending on the language, so use "any" or "all" to clarify.  (Matlab seems to default to "all", though it may depend on context.)
+
Index: /issm/trunk/test/NightlyRun/runme.m
===================================================================
--- /issm/trunk/test/NightlyRun/runme.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/runme.m	(revision 13975)
@@ -67,5 +67,5 @@
 end
 % }}}
-%GET RANK and NUMPROCS for mutlithreaded runs  {{{
+%GET RANK and NUMPROCS for multithreaded runs  {{{
 rank=getfieldvalue(options,'rank',1);
 numprocs=getfieldvalue(options,'numprocs',1);
@@ -106,5 +106,5 @@
 	test_ids=intersect(test_ids,[1401:1499]);
 elseif strcmpi(benchmark,'adolc'),
-	test_ids=intersect(test_ids,[3001:3010]);
+	test_ids=intersect(test_ids,[3001:3020]);
 elseif strcmpi(benchmark,'validation'),
 	test_ids=intersect(test_ids,[1001:1999]);
Index: /issm/trunk/test/NightlyRun/runme.py
===================================================================
--- /issm/trunk/test/NightlyRun/runme.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/runme.py	(revision 13975)
@@ -50,5 +50,5 @@
 	#Process options
 	#GET benchmark {{{
-	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing']):
+	if not ismember(benchmark,['all','nightly','ismip','eismint','thermal','mesh','validation','tranforcing','adolc']):
 		print "runme warning: benchmark '%s' not supported, defaulting to test 'nightly'." % benchmark
 		benchmark='nightly'
@@ -107,4 +107,6 @@
 	elif strcmpi(benchmark,'mesh'):
 		test_ids=test_ids.intersection(set(range(1401,1500)))
+	elif strcmpi(benchmark,'adolc'):
+		test_ids=test_ids.intersection(set(range(3001,3020)))
 	elif strcmpi(benchmark,'validation'):
 		test_ids=test_ids.intersection(set(range(1001,2000)))
@@ -215,5 +217,5 @@
 			message=me
 			if   strcmpi(output,'nightly'):
-				fid=open(os.path.join(ISSM_DIR+'nightlylog','pythonerror.log'), 'a')
+				fid=open(os.path.join(ISSM_DIR,'nightlylog','pythonerror.log'), 'a')
 				fid.write('%s' % message)
 				fid.write('\n------------------------------------------------------------------\n')
@@ -221,5 +223,5 @@
 				print 'FAILURE difference: N/A test id: %i test name: %s field: %s' % (id,id_string,'N/A')
 			elif strcmpi(output,'daily'):
-				fid=open(os.path.join(ISSM_DIR+'dailylog','pythonerror.log'), 'a')
+				fid=open(os.path.join(ISSM_DIR,'dailylog','pythonerror.log'), 'a')
 				fid.write('%s' % message)
 				fid.write('\n------------------------------------------------------------------\n')
@@ -262,4 +264,6 @@
 	md = runme(args.id, args.exclude, args.benchmark, args.procedure, args.output, args.rank, args.numprocs)
 
+	if strcmpi(args.output,'nightly'):
+		print "PYTHONEXITEDCORRECTLY"
+
 	exit(md)
-
Index: /issm/trunk/test/NightlyRun/test101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test101.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test101.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',50000);
+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);
+md.diagnostic.requested_outputs=StressTensorEnum();
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test101.py
===================================================================
--- /issm/trunk/test/NightlyRun/test101.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test101.py	(revision 13975)
@@ -22,10 +22,10 @@
 	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'],\
+	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/test102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test102.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test102.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test102.py
===================================================================
--- /issm/trunk/test/NightlyRun/test102.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test102.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,2)
+md.extrude(3,2.)
 md=setflowequation(md,'macayeal','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -20,9 +20,9 @@
 field_tolerances=[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]['Vz'],\
-	md.results['DiagnosticSolution'][1]['Vel'],\
-	md.results['DiagnosticSolution'][1]['Pressure'],\
+	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/test103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test103.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test103.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+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);
+md.diagnostic.requested_outputs=StressTensorEnum();
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test103.py
===================================================================
--- /issm/trunk/test/NightlyRun/test103.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test103.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,2)
+md.extrude(3,2.)
 md=setflowequation(md,'pattyn','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -23,14 +23,14 @@
 	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'],\
+	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/test104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test104.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test104.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test104.py
===================================================================
--- /issm/trunk/test/NightlyRun/test104.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test104.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,2)
+md.extrude(3,2.)
 md=setflowequation(md,'stokes','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -20,8 +20,8 @@
 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'],\
+	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/test105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test105.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test105.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test105.py
===================================================================
--- /issm/trunk/test/NightlyRun/test105.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test105.py	(revision 13975)
@@ -19,4 +19,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['PrognosticSolution'][1]['Thickness'],\
+	md.results.PrognosticSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test106.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test106.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
 md=setmask(md,'all','');
@@ -7,5 +7,5 @@
 md.prognostic.stabilization=3;
 md.prognostic.spcthickness=md.geometry.thickness;
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test106.py
===================================================================
--- /issm/trunk/test/NightlyRun/test106.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test106.py	(revision 13975)
@@ -23,4 +23,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['PrognosticSolution'][1]['Thickness'],\
+	md.results.PrognosticSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test107.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test107.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,5,3.);
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test107.py
===================================================================
--- /issm/trunk/test/NightlyRun/test107.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test107.py	(revision 13975)
@@ -12,5 +12,5 @@
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
 md=setflowequation(md,'macayeal','all')
-md.extrude(5,3)
+md.extrude(5,3.)
 md.cluster=generic('name',oshostname(),'np',3)
 md=solve(md,PrognosticSolutionEnum())
@@ -20,4 +20,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['PrognosticSolution'][1]['Thickness'],\
+	md.results.PrognosticSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test108.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test108.m	(revision 13975)
@@ -1,14 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+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,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_tolerances={1e-13,1e-5};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
Index: /issm/trunk/test/NightlyRun/test108.py
===================================================================
--- /issm/trunk/test/NightlyRun/test108.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test108.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+md.extrude(3,1.)
 md=setflowequation(md,'macayeal','all')
 md.timestepping.time_step=0
@@ -19,7 +19,7 @@
 #Fields and tolerances to track changes
 field_names     =['Temperature','BasalforcingsMeltingRate']
-field_tolerances=[1e-13,1e-13]
+field_tolerances=[1e-13,1e-5]
 field_values=[\
-	md.results['ThermalSolution'][1]['Temperature'],\
-	md.results['ThermalSolution'][1]['BasalforcingsMeltingRate'],\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsMeltingRate,\
 	]
Index: /issm/trunk/test/NightlyRun/test109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test109.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test109.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -9,5 +9,5 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test109.py
===================================================================
--- /issm/trunk/test/NightlyRun/test109.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test109.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+md.extrude(3,1.)
 md=setflowequation(md,'macayeal','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -24,5 +24,5 @@
 field_tolerances=[1e-13,1e-13]
 field_values=[\
-	md.results['TransientSolution'][1]['Temperature'],\
-	md.results['TransientSolution'][1]['BasalforcingsMeltingRate'],\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
 	]
Index: /issm/trunk/test/NightlyRun/test110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test110.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test110.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
@@ -6,5 +6,5 @@
 md.transient.requested_outputs=IceVolumeEnum();
 
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test110.py
===================================================================
--- /issm/trunk/test/NightlyRun/test110.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test110.py	(revision 13975)
@@ -23,27 +23,27 @@
 						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'],\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].IceVolume,\
+	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,\
 	]
Index: /issm/trunk/test/NightlyRun/test1101.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1101.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1101.m	(revision 13975)
@@ -12,9 +12,9 @@
 	nx=20; %numberof nodes in x direction
 	ny=20;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPA.par');
-	md=extrude(md,9,1);
+	md=extrude(md,9,1.);
 
 	md=setflowequation(md,'pattyn','all');
@@ -40,5 +40,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1102.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1102.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1102.m	(revision 13975)
@@ -12,5 +12,5 @@
 	nx=20; %numberof nodes in x direction
 	ny=20;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
@@ -24,5 +24,5 @@
 
 	md=parameterize(md,'../Par/ISMIPA.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 	md=setflowequation(md,'stokes','all');
 
@@ -49,5 +49,5 @@
 	md.diagnostic.restol=1;
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1103.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1103.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1103.m	(revision 13975)
@@ -10,9 +10,9 @@
 	nx=20; %numberof nodes in x direction
 	ny=20;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPB.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	md=setflowequation(md,'pattyn','all');
@@ -37,5 +37,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1104.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1104.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1104.m	(revision 13975)
@@ -9,9 +9,9 @@
 	nx=20; %numberof nodes in x direction
 	ny=20;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPB.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 	md=setflowequation(md,'pattyn','all');
 
@@ -37,5 +37,5 @@
 	md.diagnostic.abstol=NaN;
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 	pos=find(md.mesh.x==0 | md.mesh.y==0 | md.mesh.x==max(md.mesh.x) | md.mesh.y==max(md.mesh.y));
 	md.diagnostic.spcvx(pos)=md.results.DiagnosticSolution.Vx(pos);
@@ -43,5 +43,5 @@
 	md.diagnostic.vertex_pairing=[];
 	md=setflowequation(md,'stokes','all');
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1105.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1105.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1105.m	(revision 13975)
@@ -12,9 +12,9 @@
 	nx=30; %number of nodes in x direction
 	ny=30;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPC.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	md=setflowequation(md,'pattyn','all'); 
@@ -63,5 +63,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1106.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1106.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1106.m	(revision 13975)
@@ -7,9 +7,9 @@
 for i=1:length(L_list),
 	L=L_list{i};  
-	md=triangle(model,['../Exp/Square_' num2str(L) '.exp'],L/10); %size 3*L 
+	md=triangle(model(),['../Exp/Square_' num2str(L) '.exp'],L/10.); %size 3*L 
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPC.par');
 	md.friction.coefficient=sqrt(md.constants.yts.*(1000+1000*sin(md.mesh.x*2*pi/L).*sin(md.mesh.y*2*pi/L)));
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	%Add spc on the borders
@@ -41,5 +41,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1107.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1107.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1107.m	(revision 13975)
@@ -12,9 +12,9 @@
 	nx=30; %numberof nodes in x direction
 	ny=30;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPD.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	md=setflowequation(md,'pattyn','all');
@@ -58,5 +58,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1108.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1108.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1108.m	(revision 13975)
@@ -9,9 +9,9 @@
 	nx=30; %numberof nodes in x direction
 	ny=30;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPD.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	md=setflowequation(md,'pattyn','all');
@@ -39,5 +39,5 @@
 	md.cluster=generic('name',oshostname(),'np',8);
 	md.verbose=verbose('convergence',true);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 	md.diagnostic.reltol=NaN;
 	md.diagnostic.abstol=NaN;
@@ -51,5 +51,5 @@
 	md.diagnostic.spcvy(pos)=md.results.DiagnosticSolution.Vy(pos);
 	md=setflowequation(md,'stokes','all');
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	%Plot the results and save them
Index: /issm/trunk/test/NightlyRun/test1109.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1109.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1109.m	(revision 13975)
@@ -13,9 +13,9 @@
 	nx=3; %number of nodes in x direction
 	ny=51;
-	md=model;
+	md=model();
 	md=squaremesh(md,Lx,Ly,nx,ny);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPE.par');
-	md=extrude(md,10,1);
+	md=extrude(md,10,1.);
 
 	if i==1 | i==3,
@@ -49,5 +49,5 @@
 	%Compute the diagnostic
 	md.cluster=generic('name',oshostname(),'np',8);
-	md=solve(md,DiagnosticSolutionEnum);
+	md=solve(md,DiagnosticSolutionEnum());
 
 	vx=(md.results.DiagnosticSolution.Vx);
Index: /issm/trunk/test/NightlyRun/test111.m
===================================================================
--- /issm/trunk/test/NightlyRun/test111.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test111.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+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);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -15,5 +15,5 @@
 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,2e-11,...
 	1e-09,1e-09,1e-08,1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-05,1e-11};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test111.py
===================================================================
--- /issm/trunk/test/NightlyRun/test111.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test111.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+md.extrude(3,1.)
 md=setflowequation(md,'pattyn','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -24,39 +24,39 @@
 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,2e-11,\
 	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'],\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].IceVolume,\
+	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,\
 	]
Index: /issm/trunk/test/NightlyRun/test1110.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1110.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1110.m	(revision 13975)
@@ -7,10 +7,10 @@
 	nx=30; %numberof nodes in x direction
 	ny=30;
-	md=model;
+	md=model();
 	md=squaremesh(md,L,L,nx,ny);
-	%md=triangle(md,'../Exp/SquareISMIP.exp',5500);
+	%md=triangle(md,'../Exp/SquareISMIP.exp',5500.);
 	md=setmask(md,'',''); %ice sheet test
 	md=parameterize(md,'../Par/ISMIPF.par');
-	md=extrude(md,4,1);
+	md=extrude(md,4,1.);
 
 	if (i==1 | i==2),
@@ -57,5 +57,5 @@
 	md.cluster=generic('name',oshostname(),'np',8);
 	md.verbose=verbose('convergence',true,'solution',true);
-	md=solve(md,TransientSolutionEnum);
+	md=solve(md,TransientSolutionEnum());
 
 	%save the results
Index: /issm/trunk/test/NightlyRun/test112.m
===================================================================
--- /issm/trunk/test/NightlyRun/test112.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test112.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,SurfaceSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test112.py
===================================================================
--- /issm/trunk/test/NightlyRun/test112.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test112.py	(revision 13975)
@@ -19,5 +19,5 @@
 field_tolerances=[1e-13,1e-13]
 field_values=[\
-	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeX'],\
-	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeY'],\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
 	]
Index: /issm/trunk/test/NightlyRun/test113.m
===================================================================
--- /issm/trunk/test/NightlyRun/test113.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test113.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
+md=extrude(md,5,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
+md=solve(md,SurfaceSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test113.py
===================================================================
--- /issm/trunk/test/NightlyRun/test113.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test113.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(5,1)
+md.extrude(5,1.)
 md=setflowequation(md,'macayeal','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -20,5 +20,5 @@
 field_tolerances=[1e-13,1e-13]
 field_values=[\
-	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeX'],\
-	md.results['SurfaceSlopeSolution'][1]['SurfaceSlopeY'],\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeX,\
+	md.results.SurfaceSlopeSolution.SurfaceSlopeY,\
 	]
Index: /issm/trunk/test/NightlyRun/test114.m
===================================================================
--- /issm/trunk/test/NightlyRun/test114.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test114.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,BedSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test114.py
===================================================================
--- /issm/trunk/test/NightlyRun/test114.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test114.py	(revision 13975)
@@ -19,5 +19,5 @@
 field_tolerances=[1e-13,1e-13]
 field_values=[\
-	md.results['BedSlopeSolution'][1]['BedSlopeX'],\
-	md.results['BedSlopeSolution'][1]['BedSlopeY'],\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
 	]
Index: /issm/trunk/test/NightlyRun/test115.m
===================================================================
--- /issm/trunk/test/NightlyRun/test115.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test115.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
+md=extrude(md,5,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
+md=solve(md,BedSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test115.py
===================================================================
--- /issm/trunk/test/NightlyRun/test115.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test115.py	(revision 13975)
@@ -11,5 +11,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(5,1)
+md.extrude(5,1.)
 md=setflowequation(md,'macayeal','all')
 md.cluster=generic('name',oshostname(),'np',3)
@@ -20,5 +20,5 @@
 field_tolerances=[1e-13,1e-13]
 field_values=[\
-	md.results['BedSlopeSolution'][1]['BedSlopeX'],\
-	md.results['BedSlopeSolution'][1]['BedSlopeY'],\
+	md.results.BedSlopeSolution.BedSlopeX,\
+	md.results.BedSlopeSolution.BedSlopeY,\
 	]
Index: /issm/trunk/test/NightlyRun/test116.m
===================================================================
--- /issm/trunk/test/NightlyRun/test116.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test116.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
@@ -7,5 +7,5 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test116.py
===================================================================
--- /issm/trunk/test/NightlyRun/test116.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test116.py	(revision 13975)
@@ -23,4 +23,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['BalancethicknessSolution'][1]['Thickness'],\
+	md.results.BalancethicknessSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test117.m
===================================================================
--- /issm/trunk/test/NightlyRun/test117.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test117.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,5,1);
+md=extrude(md,5,1.);
 %Add boundary conditions on thickness on the border
 pos=find(md.mesh.vertexonboundary);
@@ -8,5 +8,5 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test117.py
===================================================================
--- /issm/trunk/test/NightlyRun/test117.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test117.py	(revision 13975)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(5,1)
+md.extrude(5,1.)
 #Add boundary conditions on thickness on the border
 pos=numpy.nonzero(md.mesh.vertexonboundary)
@@ -24,4 +24,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['BalancethicknessSolution'][1]['Thickness'],\
+	md.results.BalancethicknessSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test118.m
===================================================================
--- /issm/trunk/test/NightlyRun/test118.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test118.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
 md=setmask(md,'all','');
@@ -7,5 +7,5 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test118.py
===================================================================
--- /issm/trunk/test/NightlyRun/test118.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test118.py	(revision 13975)
@@ -23,4 +23,4 @@
 field_tolerances=[1e-13]
 field_values=[\
-	md.results['BalancethicknessSolution'][1]['Thickness'],\
+	md.results.BalancethicknessSolution.Thickness,\
 	]
Index: /issm/trunk/test/NightlyRun/test119.m
===================================================================
--- /issm/trunk/test/NightlyRun/test119.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test119.m	(revision 13975)
@@ -1,10 +1,10 @@
 
 %Simple mesh
-md=bamg(model,'domain','../Exp/Square.exp','hmax',100000);
+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]');
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',300000.,'hVertices',[10000. 100000. 400000. 100000.]');
 x2=md.mesh.x;
 y2=md.mesh.y;
@@ -12,11 +12,11 @@
 %big mesh
 t0=clock;
-md=bamg(model,'domain','../Exp/Square.exp','hmax',3000);
+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_names     ={'x1','y1','x2','y2','nbelements','elapsed time'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,0.7};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test119.py
===================================================================
--- /issm/trunk/test/NightlyRun/test119.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test119.py	(revision 13975)
@@ -0,0 +1,30 @@
+import numpy
+import time
+from model import *
+from bamg import *
+from MatlabFuncs import *
+
+#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',numpy.array([10000.,100000.,400000.,100000.]).reshape(-1,1))
+x2=md.mesh.x
+y2=md.mesh.y
+
+#big mesh
+t0=time.time()
+md=bamg(model(),'domain','../Exp/Square.exp','hmax',3000.)
+nbelements=md.mesh.numberofelements
+elapsedtime=time.time()-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.7]
+field_values=[\
+	x1, y1,\
+	x2, y2,\
+	nbelements,elapsedtime,\
+	]
Index: /issm/trunk/test/NightlyRun/test120.m
===================================================================
--- /issm/trunk/test/NightlyRun/test120.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test120.m	(revision 13975)
@@ -1,11 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+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);
+md=solve(md,EnthalpySolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test120.py
===================================================================
--- /issm/trunk/test/NightlyRun/test120.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test120.py	(revision 13975)
@@ -12,5 +12,5 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+md.extrude(3,1.)
 md=setflowequation(md,'macayeal','all')
 md.timestepping.time_step=0
@@ -23,6 +23,6 @@
 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'],\
+	md.results.EnthalpySolution.Enthalpy,\
+	md.results.EnthalpySolution.Waterfraction,\
+	md.results.EnthalpySolution.Temperature,\
 	]
Index: /issm/trunk/test/NightlyRun/test1201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1201.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1201.m	(revision 13975)
@@ -6,5 +6,5 @@
 for stabilization=1:3;
 	%The goal is to test the prognostic model
-	md=bamg(model,'domain','../Exp/SquareEISMINT.exp','hmax',3000);
+	md=bamg(model(),'domain','../Exp/SquareEISMINT.exp','hmax',3000);
 	md=setmask(md,'all','');
 	md=parameterize(md,'../Par/SquareEISMINT.par');
@@ -38,5 +38,5 @@
 	md.settings.output_frequency=500; %keep only last step
 	md.verbose=verbose();
-	md=solve(md,TransientSolutionEnum);
+	md=solve(md,TransientSolutionEnum());
 	results{stabilization}=(md.results.TransientSolution(end).Thickness);
 end
Index: /issm/trunk/test/NightlyRun/test1202.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1202.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1202.m	(revision 13975)
@@ -3,6 +3,6 @@
 
 %tests 3 and 4: using Glen's flow law
-md=model;
-md=triangle(md,'../Exp/SquareEISMINT.exp',3550);
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
@@ -11,5 +11,5 @@
 %Compute solution for MacAyeal's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1203.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1203.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1203.m	(revision 13975)
@@ -3,6 +3,6 @@
 
 %test 5 and 6 : 
-md=model;
-md=triangle(md,'../Exp/SquareEISMINT.exp',5100); %test3
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',5100.); %test3
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
@@ -15,5 +15,5 @@
 %Compute solution for MacAyeal's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 vx=(md.results.DiagnosticSolution.Vx);
Index: /issm/trunk/test/NightlyRun/test1204.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1204.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1204.m	(revision 13975)
@@ -3,6 +3,6 @@
 
 %tests 3 and 4: using Glen's flow law
-md=model;
-md=triangle(md,'../Exp/SquareEISMINT.exp',3550);
+md=model();
+md=triangle(md,'../Exp/SquareEISMINT.exp',3550.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareEISMINT.par');
@@ -15,5 +15,5 @@
 %Compute solution for MacAyeal's model 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %plot results
@@ -24,5 +24,5 @@
 md.timestepping.final_time=5000;
 md.prognostic.stabilization=1;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 plotmodel(md,'data',(md.results.TransientSolution(end).Vx))
Index: /issm/trunk/test/NightlyRun/test1205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1205.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1205.m	(revision 13975)
@@ -6,5 +6,5 @@
 
 %To begin with the numerical model
-md=model;
+md=model();
 md=roundmesh(md,750000,resolution);
 md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
@@ -18,5 +18,5 @@
 
 %We extrude the model to have a 3d model
-md=extrude(md,numlayers,1);
+md=extrude(md,numlayers,1.);
 md=setflowequation(md,'hutter','all');
 
@@ -29,5 +29,5 @@
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
Index: /issm/trunk/test/NightlyRun/test1206.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1206.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1206.m	(revision 13975)
@@ -6,5 +6,5 @@
 
 %To begin with the numerical model
-md=model;
+md=model();
 md=roundmesh(md,750000,resolution);
 md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
@@ -18,5 +18,5 @@
 
 %We extrude the model to have a 3d model
-md=extrude(md,numlayers,1);
+md=extrude(md,numlayers,1.);
 md=setflowequation(md,'pattyn','all');
 
@@ -29,5 +29,5 @@
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
Index: /issm/trunk/test/NightlyRun/test1207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1207.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1207.m	(revision 13975)
@@ -6,5 +6,5 @@
 
 %To begin with the numerical model
-md=model;
+md=model();
 md=roundmesh(md,750000,resolution);
 md=setmask(md,'',''); %We can not test iceshelves nor ice rises with this analytical solution
@@ -18,5 +18,5 @@
 
 %We extrude the model to have a 3d model
-md=extrude(md,numlayers,1);
+md=extrude(md,numlayers,1.);
 md=setflowequation(md,'stokes','all');
 
@@ -29,5 +29,5 @@
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Calculate the depth averaged velocity field (2d):
Index: /issm/trunk/test/NightlyRun/test1208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1208.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1208.m	(revision 13975)
@@ -4,10 +4,10 @@
 
 %To begin with the numerical model
-md=triangle(model,'../Exp/SquareEISMINT750000.exp',resolution);
+md=triangle(model(),'../Exp/SquareEISMINT750000.exp',resolution);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/RoundSheetEISMINT.par');
 
 %We extrude the model to have a 3d model
-md=extrude(md,numlayers,1);
+md=extrude(md,numlayers,1.);
 md=setflowequation(md,'hutter','all');
 
@@ -27,5 +27,5 @@
 %Now we can solve the problem 
 md.cluster=generic('name',oshostname(),'np',8);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test121.m
===================================================================
--- /issm/trunk/test/NightlyRun/test121.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test121.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -11,5 +11,5 @@
 md.transient.isgroundingline=0;
 md.thermal.isenthalpy=1;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test121.py
===================================================================
--- /issm/trunk/test/NightlyRun/test121.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test121.py	(revision 13975)
@@ -11,8 +11,8 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+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.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
 md.transient.isdiagnostic=0
 md.transient.isprognostic=0
@@ -28,12 +28,12 @@
 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'],\
+	md.results.TransientSolution[0].Enthalpy,\
+	md.results.TransientSolution[0].Waterfraction,\
+	md.results.TransientSolution[0].Temperature,\
+	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,\
 	]
Index: /issm/trunk/test/NightlyRun/test122.m
===================================================================
--- /issm/trunk/test/NightlyRun/test122.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test122.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
@@ -8,10 +8,10 @@
 md.thermal.stabilization=2;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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'};
+	'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,...
Index: /issm/trunk/test/NightlyRun/test122.py
===================================================================
--- /issm/trunk/test/NightlyRun/test122.py	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test122.py	(revision 13975)
@@ -11,7 +11,7 @@
 md=setmask(md,'all','')
 md=parameterize(md,'../Par/SquareShelfConstrained.py')
-md.extrude(3,1)
+md.extrude(3,1.)
 md=setflowequation(md,'pattyn','all')
-md.initialization.waterfraction=numpy.zeros(md.mesh.numberofvertices)
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
 md.thermal.isenthalpy=1
 md.thermal.stabilization=2
@@ -21,6 +21,6 @@
 #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']
+	'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,\
@@ -28,36 +28,36 @@
 	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'],\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].Enthalpy,\
+	md.results.TransientSolution[0].Waterfraction,\
+	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,\
 	]
Index: /issm/trunk/test/NightlyRun/test1301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1301.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1301.m	(revision 13975)
@@ -5,9 +5,9 @@
 printingflag=false;
 
-md=model;
-md=triangle(md,'../Exp/Square.exp',100000);
+md=model();
+md=triangle(md,'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareThermal.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'Pattyn','all');
 
@@ -26,5 +26,5 @@
 %modeled  results
 md.cluster=generic('name',oshostname(),'np',2);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1302.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1302.m	(revision 13975)
@@ -4,9 +4,9 @@
 printingflag=false;
 
-md=model;
-md=triangle(md,'../Exp/Square.exp',100000);
+md=model();
+md=triangle(md,'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareThermal.par');
-md=extrude(md,30,1);   %NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%)
+md=extrude(md,30,1.);   %NB: the more one extrudes, the better (10-> relative~0.35%, 20->0.1%, 30->0.05%)
 md=setflowequation(md,'Pattyn','all'); 
 
@@ -28,5 +28,5 @@
 %modeled  results
 md.cluster=generic('name',oshostname(),'np',2);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1303.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1303.m	(revision 13975)
@@ -5,9 +5,9 @@
 printingflag=false;
 
-md=model;
-md=triangle(md,'../Exp/Square.exp',100000);
+md=model();
+md=triangle(md,'../Exp/Square.exp',100000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareThermal.par');
-md=extrude(md,11,2);
+md=extrude(md,11,2.);
 md=setflowequation(md,'Pattyn','all');
 pos1=find(md.mesh.elementonbed);     md.thermal.spctemperature(md.mesh.elements(pos1,1:3))=10;
@@ -22,5 +22,5 @@
 %modeled  results
 md.cluster=generic('name',oshostname(),'np',2);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1304.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1304.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1304.m	(revision 13975)
@@ -5,9 +5,9 @@
 printingflag=false;
 
-md=model;
-md=triangle(md,'../Exp/Square.exp',100000);
+md=model();
+md=triangle(md,'../Exp/Square.exp',100000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareThermal.par');
-md=extrude(md,11,1);
+md=extrude(md,11,1.);
 md=setflowequation(md,'Pattyn','all');
 
@@ -23,5 +23,5 @@
 %modeled  results
 md.cluster=generic('name',oshostname(),'np',2);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %plot results
Index: /issm/trunk/test/NightlyRun/test1401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1401.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1401.m	(revision 13975)
@@ -7,5 +7,5 @@
 nx=70; %numberof nodes in x direction
 ny=70;
-md=model;
+md=model();
 
 %mesh adaptation loop YAMS
@@ -72,6 +72,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'xyams' 'yyams' 'xbamg' 'ybamg'};
-field_tolerances={1e-13 1e-13 1e-13 1e-13};
+field_names     ={'xyams','yyams','xbamg','ybamg'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test1402.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1402.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1402.m	(revision 13975)
@@ -6,5 +6,5 @@
 nx=30; %numberof nodes in x direction
 ny=30;
-md=model;
+md=model();
 
 %mesh adaptation loop YAMS
@@ -102,6 +102,6 @@
 
 %Fields and tolerances to track changes
-field_names     ={'xyams' 'yyams' 'xbamg' 'ybamg'};
-field_tolerances={1e-13 1e-13 1e-13 1e-13};
+field_names     ={'xyams','yyams','xbamg','ybamg'};
+field_tolerances={1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test1501.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1501.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1501.m	(revision 13975)
@@ -1,5 +1,5 @@
 printingflag = false;
 
-md=triangle(model,'../Exp/Square.exp',350000);
+md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -8,17 +8,17 @@
 md.transient.isthermal=0;
 
-md.timestepping.time_step=1;
+md.timestepping.time_step=1.;
 md.settings.output_frequency=1;
-md.timestepping.final_time=2000;
+md.timestepping.final_time=2000.;
 
 %Solve for thinning rate -> -1 * surface mass balance
-smb= 2*ones(md.mesh.numberofvertices,1);   
+smb= 2.*ones(md.mesh.numberofvertices,1);   
 md.surfaceforcings.mass_balance= smb;
 md.basalforcings.melting_rate= smb;
 
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 for i=1:10
-	 md=solve(md,PrognosticSolutionEnum);
+	 md=solve(md,PrognosticSolutionEnum());
 	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
 end
@@ -27,11 +27,11 @@
 smb = md.surfaceforcings.mass_balance;
 
-tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ];
+tooth= [ [ones(400,1)*(smb') - 10.]' [ones(400,1)*(smb')]' ];
 smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
 
 md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1:2000];
-
-md=solve(md,TransientSolutionEnum);
+md.surfaceforcings.mass_balance(end+1,:)=[1.:2000.];
+
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1502.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1502.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1502.m	(revision 13975)
@@ -1,25 +1,25 @@
 printingflag = false;
 
-md=triangle(model,'../Exp/Square.exp',450000);
+md=triangle(model(),'../Exp/Square.exp',450000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 md=setflowequation(md,'macayeal','all');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md.cluster=generic('name',oshostname(),'np',2);
 md.transient.isthermal=0;
 
-md.timestepping.time_step=1;
+md.timestepping.time_step=1.;
 md.settings.output_frequency=1;
-md.timestepping.final_time=2000;
+md.timestepping.final_time=2000.;
 
 %Solve for thinning rate -> -1 * surface mass balance
-smb= 2*ones(md.mesh.numberofvertices,1);   
+smb= 2.*ones(md.mesh.numberofvertices,1);   
 md.surfaceforcings.mass_balance= smb;
 md.basalforcings.melting_rate= smb;
 
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 for i=1:10
-	 md=solve(md,PrognosticSolutionEnum);
+	 md=solve(md,PrognosticSolutionEnum());
 	 md.surfaceforcings.mass_balance= md.surfaceforcings.mass_balance - ((md.results.PrognosticSolution.Thickness)-md.geometry.thickness);
 end
@@ -28,11 +28,11 @@
 smb = md.surfaceforcings.mass_balance;
 
-tooth= [ [ones(400,1)*(smb') - 10]' [ones(400,1)*(smb')]' ];
+tooth= [ [ones(400,1)*(smb') - 10.]' [ones(400,1)*(smb')]' ];
 smb=[ [ones(399,1)*(smb')]' smb  tooth tooth];
 
 md.surfaceforcings.mass_balance= smb;
-md.surfaceforcings.mass_balance(end+1,:)=[1:2000];
-
-md=solve(md,TransientSolutionEnum);
+md.surfaceforcings.mass_balance(end+1,:)=[1.:2000.];
+
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test1601.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1601.m	(revision 13975)
@@ -1,16 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
 md=setflowequation(md,'macayeal','all');
-md.diagnostic.spcvx(find(md.mesh.y>0))=NaN;
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
+md.diagnostic.spcvx(find(md.mesh.y>0.))=NaN;
+md.initialization.vx(:)=0.;
+md.initialization.vy(:)=0.;
+md.initialization.vel(:)=0.;
 
-md.cluster=generic('name',oshostname,'np',2);
-md=solve(md,DiagnosticSolutionEnum);
+md.cluster=generic('name',oshostname(),'np',2);
+md=solve(md,DiagnosticSolutionEnum());
 vel0=md.results.DiagnosticSolution.Vel;
 
-theta=30*pi/180;
+theta=30.*pi/180.;
 x=md.mesh.x;
 y=md.mesh.y;
@@ -20,5 +20,5 @@
 md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
 md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 vel1=md.results.DiagnosticSolution.Vel;
 
@@ -27,9 +27,9 @@
 
 %Now, put CS back to normal except on the side where the spc are applied
-pos=find(x==0 | x==1000000);
+pos=find(x==0. | x==1000000.);
 md.diagnostic.referential(:)=NaN;
 md.diagnostic.referential(pos,1:3)=repmat([cos(theta),sin(theta),0],size(pos,1),1);
 md.diagnostic.referential(pos,4:6)=repmat([0,0,1],size(pos,1),1);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 vel2=md.results.DiagnosticSolution.Vel;
 
Index: /issm/trunk/test/NightlyRun/test1601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1601.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test1601.py	(revision 13975)
@@ -0,0 +1,56 @@
+import numpy
+import sys
+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/SquareShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.diagnostic.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.initialization.vel=numpy.zeros_like(md.initialization.vx)
+
+md.cluster=generic('name',oshostname(),'np',2)
+md=solve(md,DiagnosticSolutionEnum())
+vel0=md.results.DiagnosticSolution.Vel
+
+theta=30.*numpy.pi/180.
+x=md.mesh.x
+y=md.mesh.y
+md.mesh.x=numpy.cos(theta)*x-numpy.sin(theta)*y
+md.mesh.y=numpy.sin(theta)*x+numpy.cos(theta)*y
+
+md.diagnostic.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.diagnostic.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,DiagnosticSolutionEnum())
+vel1=md.results.DiagnosticSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+print "Error between Cartesian and rotated CS: %g" % (numpy.max(numpy.abs(vel0-vel1))/(numpy.max(numpy.abs(vel0))+sys.float_info.epsilon))
+
+#Now, put CS back to normal except on the side where the spc are applied
+pos=numpy.nonzero(numpy.logical_or(x==0.,x==1000000.))[0]
+md.diagnostic.referential[:]=float('NaN')
+md.diagnostic.referential[pos,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(len(pos),1))
+md.diagnostic.referential[pos,3: ]=numpy.tile([0,0,1],(len(pos),1))
+md=solve(md,DiagnosticSolutionEnum())
+vel2=md.results.DiagnosticSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel2,'data',vel2-vel0,'title','Cartesian CS','title','Rotated CS','title','difference')
+print "Error between Cartesian and rotated CS: %g" % (numpy.max(numpy.abs(vel0-vel2))/(numpy.max(numpy.abs(vel0))+sys.float_info.epsilon))
+
+#Fields and tolerances to track changes
+field_names     =['vel1','vel2']
+field_tolerances=[1e-11,1e-11]
+field_values=[\
+	vel1, \
+	vel2, \
+	]
Index: /issm/trunk/test/NightlyRun/test1602.m
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test1602.m	(revision 13975)
@@ -1,17 +1,17 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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,5,1.);
 md=setflowequation(md,'pattyn','all');
-md.diagnostic.spcvx(find(md.mesh.y>0))=NaN;
-md.initialization.vx(:)=0;
-md.initialization.vy(:)=0;
-md.initialization.vel(:)=0;
+md.diagnostic.spcvx(find(md.mesh.y>0.))=NaN;
+md.initialization.vx(:)=0.;
+md.initialization.vy(:)=0.;
+md.initialization.vel(:)=0.;
 
-md.cluster=generic('name',oshostname,'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md.cluster=generic('name',oshostname(),'np',3);
+md=solve(md,DiagnosticSolutionEnum());
 vel0=md.results.DiagnosticSolution.Vel;
 
-theta=30*pi/180;
+theta=30.*pi/180.;
 x=md.mesh.x;
 y=md.mesh.y;
@@ -21,5 +21,5 @@
 md.diagnostic.referential(:,1:3)=repmat([cos(theta),sin(theta),0],md.mesh.numberofvertices,1);
 md.diagnostic.referential(:,4:6)=repmat([0,0,1],md.mesh.numberofvertices,1);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 vel1=md.results.DiagnosticSolution.Vel;
 
Index: /issm/trunk/test/NightlyRun/test1602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test1602.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test1602.py	(revision 13975)
@@ -0,0 +1,45 @@
+import numpy
+import sys
+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,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'pattyn','all')
+md.diagnostic.spcvx[numpy.nonzero(md.mesh.y>0.)]=float('NaN')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.initialization.vel=numpy.zeros_like(md.initialization.vx)
+
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,DiagnosticSolutionEnum())
+vel0=md.results.DiagnosticSolution.Vel
+
+theta=30.*numpy.pi/180.
+x=md.mesh.x
+y=md.mesh.y
+md.mesh.x=numpy.cos(theta)*x-numpy.sin(theta)*y
+md.mesh.y=numpy.sin(theta)*x+numpy.cos(theta)*y
+
+md.diagnostic.referential[:,0:3]=numpy.tile([numpy.cos(theta),numpy.sin(theta),0],(md.mesh.numberofvertices,1))
+md.diagnostic.referential[:,3: ]=numpy.tile([0,0,1],(md.mesh.numberofvertices,1))
+md=solve(md,DiagnosticSolutionEnum())
+vel1=md.results.DiagnosticSolution.Vel
+
+#plotmodel(md,'data',vel0,'data',vel1,'data',vel1-vel0,'title','Cartesian CS','title','Rotated CS','title','difference','view#all',2)
+print "Error between Cartesian and rotated CS: %g" % (numpy.max(numpy.abs(vel0-vel1))/(numpy.max(numpy.abs(vel0))+sys.float_info.epsilon))
+
+#Fields and tolerances to track changes
+field_names     =['vel1']
+field_tolerances=[1e-9]
+field_values=[\
+	vel1, \
+	];
Index: /issm/trunk/test/NightlyRun/test201.m
===================================================================
--- /issm/trunk/test/NightlyRun/test201.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test201.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test201.py
===================================================================
--- /issm/trunk/test/NightlyRun/test201.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test201.py	(revision 13975)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+from ContourToMesh import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+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 13974)
+++ /issm/trunk/test/NightlyRun/test202.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test202.py
===================================================================
--- /issm/trunk/test/NightlyRun/test202.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test202.py	(revision 13975)
@@ -0,0 +1,30 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.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','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 13974)
+++ /issm/trunk/test/NightlyRun/test203.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test203.py
===================================================================
--- /issm/trunk/test/NightlyRun/test203.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test203.py	(revision 13975)
@@ -0,0 +1,30 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test204.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test204.py
===================================================================
--- /issm/trunk/test/NightlyRun/test204.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test204.py	(revision 13975)
@@ -0,0 +1,30 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.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.Vx,\
+	md.results.DiagnosticSolution.Vy,\
+	md.results.DiagnosticSolution.Vz,\
+	md.results.DiagnosticSolution.Vel,\
+	md.results.DiagnosticSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test205.m
===================================================================
--- /issm/trunk/test/NightlyRun/test205.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test205.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test205.py
===================================================================
--- /issm/trunk/test/NightlyRun/test205.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test205.py	(revision 13975)
@@ -0,0 +1,30 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test206.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test206.py
===================================================================
--- /issm/trunk/test/NightlyRun/test206.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test206.py	(revision 13975)
@@ -0,0 +1,28 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.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.Temperature,\
+	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test207.m
===================================================================
--- /issm/trunk/test/NightlyRun/test207.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test207.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -9,9 +9,9 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+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_tolerances={1e-13,1e-6,1e-13,1e-6,1e-13,1e-6};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
Index: /issm/trunk/test/NightlyRun/test207.py
===================================================================
--- /issm/trunk/test/NightlyRun/test207.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test207.py	(revision 13975)
@@ -0,0 +1,33 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.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     =['Temperature1','BasalforcingsMeltingRate1','Temperature2','BasalforcingsMeltingRate2','Temperature3','BasalforcingsMeltingRate3']
+field_tolerances=[1e-13,1e-6,1e-13,1e-6,1e-13,1e-6]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	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/test208.m
===================================================================
--- /issm/trunk/test/NightlyRun/test208.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test208.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test208.py
===================================================================
--- /issm/trunk/test/NightlyRun/test208.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test208.py	(revision 13975)
@@ -0,0 +1,45 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test209.m
===================================================================
--- /issm/trunk/test/NightlyRun/test209.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test209.m	(revision 13975)
@@ -1,14 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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'};
+	'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,...
Index: /issm/trunk/test/NightlyRun/test209.py
===================================================================
--- /issm/trunk/test/NightlyRun/test209.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test209.py	(revision 13975)
@@ -0,0 +1,60 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test210.m
===================================================================
--- /issm/trunk/test/NightlyRun/test210.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test210.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test210.py
===================================================================
--- /issm/trunk/test/NightlyRun/test210.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test210.py	(revision 13975)
@@ -0,0 +1,60 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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-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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test211.m
===================================================================
--- /issm/trunk/test/NightlyRun/test211.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test211.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test211.py
===================================================================
--- /issm/trunk/test/NightlyRun/test211.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test211.py	(revision 13975)
@@ -0,0 +1,62 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'stokes','all')
+md.diagnostic.reltol=NaN
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,TransientSolutionEnum())
+
+
+# Fields and tolerances to track changes
+
+field_names=[\
+	'Vx1','Vy1','Vz1','Vel1','Pressure1','Bed1','Surface1','Thickness1','Temperature1','BasalforcingsMeltingRate1', \
+	'Vx2','Vy2','Vz2','Vel2','Pressure2','Bed2','Surface2','Thickness2','Temperature2','BasalforcingsMeltingRate2', \
+	'Vx3','Vy3','Vz3','Vel3','Pressure3','Bed3','Surface3','Thickness3','Temperature3','BasalforcingsMeltingRate3']
+field_tolerances=[\
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,\
+	1e-08,1e-08,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06,\
+	1e-07,1e-07,1e-06,1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test212.m
===================================================================
--- /issm/trunk/test/NightlyRun/test212.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test212.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -18,12 +18,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.MaterialsRheologyBbar),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test212.py
===================================================================
--- /issm/trunk/test/NightlyRun/test212.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test212.py	(revision 13975)
@@ -0,0 +1,49 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+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.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 13974)
+++ /issm/trunk/test/NightlyRun/test213.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 
@@ -19,8 +19,8 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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={...
Index: /issm/trunk/test/NightlyRun/test213.py
===================================================================
--- /issm/trunk/test/NightlyRun/test213.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test213.py	(revision 13975)
@@ -0,0 +1,51 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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]
+#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 13974)
+++ /issm/trunk/test/NightlyRun/test214.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 
@@ -19,12 +19,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.DiagnosticSolution.Gradient1),...
-	md.results.DiagnosticSolution.J,...
+	(md.results.DiagnosticSolution.J),...
 	(md.results.DiagnosticSolution.MaterialsRheologyB),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test214.py
===================================================================
--- /issm/trunk/test/NightlyRun/test214.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test214.py	(revision 13975)
@@ -0,0 +1,50 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+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=solve(md,DiagnosticSolutionEnum())
+
+
+# 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_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/test215.m
===================================================================
--- /issm/trunk/test/NightlyRun/test215.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test215.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'stokes','all');
 
@@ -19,12 +19,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyBbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.MaterialsRheologyB),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test215.py
===================================================================
--- /issm/trunk/test/NightlyRun/test215.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test215.py	(revision 13975)
@@ -0,0 +1,50 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',200000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test216.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000);
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
 md=meshprocessrifts(md,'../Exp/Square.exp');
 md=setmask(md,'all','');
@@ -12,5 +12,5 @@
 md.diagnostic.rift_penalty_threshold=0;
 md.rifts.riftstruct.fractionincrement=.1;
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test216.py
===================================================================
--- /issm/trunk/test/NightlyRun/test216.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test216.py	(revision 13975)
@@ -0,0 +1,37 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from meshprocessrifts import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+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.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+# rift settings
+
+md.rifts.riftstruct[0]['fill']=MelangeEnum()
+md.rifts.riftstruct[0]['fraction']=0
+md.diagnostic.rift_penalty_lock=2
+md.diagnostic.rift_penalty_threshold=0
+md.rifts.riftstruct[0]['fractionincrement']=0.1
+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/test217.m
===================================================================
--- /issm/trunk/test/NightlyRun/test217.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test217.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -58,5 +58,5 @@
 md.diagnostic.icefront=diagnostic.icefront;
 
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %create analytical solution: strain rate is constant = ((rho_ice*g*h)/4B)^3 (Paterson, 4th Edition, page 292.
Index: /issm/trunk/test/NightlyRun/test217.py
===================================================================
--- /issm/trunk/test/NightlyRun/test217.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test217.py	(revision 13975)
@@ -0,0 +1,84 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from paterson import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+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=float(nan)*ones((md.mesh.numberofvertices,1))
+md.diagnostic.spcvy=float(nan)*ones((md.mesh.numberofvertices,1))
+md.diagnostic.spcvz=float(nan)*ones((md.mesh.numberofvertices,1))
+
+# constrain flanks to 0 normal velocity
+pos=numpy.nonzero(numpy.logical_or(md.mesh.x==xmin,md.mesh.x==xmax))
+md.diagnostic.spcvx[pos]=0
+md.diagnostic.spcvz[pos]=float(nan)
+
+# constrain grounding line to 0 velocity
+pos=numpy.nonzero(md.mesh.y==ymin)
+md.diagnostic.spcvx[pos]=0
+md.diagnostic.spcvy[pos]=0
+
+# icefront
+nodeonicefront=zeros(md.mesh.numberofvertices)
+pos=numpy.nonzero(md.mesh.y==ymax)
+nodeonicefront[pos]=1
+pos=numpy.nonzero(numpy.logical_or(nodeonicefront[md.mesh.segments[:,0].astype(int)-1],nodeonicefront[md.mesh.segments[:,1].astype(int)-1]))[0]
+diagnostic.icefront=md.mesh.segments[pos,:]
+diagnostic.icefront=numpy.hstack((diagnostic.icefront,1.*md.mask.elementonfloatingice[diagnostic.icefront[:,-1].astype(int)-1].reshape(-1,1)))
+md.diagnostic.icefront=diagnostic.icefront
+
+md=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 13974)
+++ /issm/trunk/test/NightlyRun/test218.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=squaremesh(model,1000000,1000000,5,5);
+md=squaremesh(model(),1000000,1000000,5,5);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -81,5 +81,5 @@
 
 %solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test219.m
===================================================================
--- /issm/trunk/test/NightlyRun/test219.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test219.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,2);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test219.py
===================================================================
--- /issm/trunk/test/NightlyRun/test219.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test219.py	(revision 13975)
@@ -0,0 +1,29 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test220.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',120000);
+md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,2,1);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test220.py
===================================================================
--- /issm/trunk/test/NightlyRun/test220.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test220.py	(revision 13975)
@@ -0,0 +1,29 @@
+from MatlabFuncs import *
+from model import *
+from EnumDefinitions import *
+from numpy import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',120000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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: /issm/trunk/test/NightlyRun/test221.m
===================================================================
--- /issm/trunk/test/NightlyRun/test221.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test221.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',120000);
+md=triangle(model(),'../Exp/Square.exp',120000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,2,1);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test221.py
===================================================================
--- /issm/trunk/test/NightlyRun/test221.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test221.py	(revision 13975)
@@ -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',120000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test222.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -5,5 +5,5 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test222.py
===================================================================
--- /issm/trunk/test/NightlyRun/test222.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test222.py	(revision 13975)
@@ -0,0 +1,43 @@
+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/SquareShelf.py')
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test223.m
===================================================================
--- /issm/trunk/test/NightlyRun/test223.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test223.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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.geometry.bed=md.geometry.bed+50.; md.geometry.surface=md.geometry.surface+50.;
+md.cluster=generic('name',oshostname(),'np',1);
 md.prognostic.hydrostatic_adjustment='Incremental';
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test223.py
===================================================================
--- /issm/trunk/test/NightlyRun/test223.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test223.py	(revision 13975)
@@ -0,0 +1,45 @@
+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/SquareShelf.py')
+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',1)
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test224.m
===================================================================
--- /issm/trunk/test/NightlyRun/test224.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test224.m	(revision 13975)
@@ -1,15 +1,15 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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);
+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'};
+	'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,...
Index: /issm/trunk/test/NightlyRun/test224.py
===================================================================
--- /issm/trunk/test/NightlyRun/test224.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test224.py	(revision 13975)
@@ -0,0 +1,58 @@
+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/SquareShelf.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test225.m
===================================================================
--- /issm/trunk/test/NightlyRun/test225.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test225.m	(revision 13975)
@@ -1,16 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+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.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);
+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'};
+	'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,...
Index: /issm/trunk/test/NightlyRun/test225.py
===================================================================
--- /issm/trunk/test/NightlyRun/test225.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test225.py	(revision 13975)
@@ -0,0 +1,60 @@
+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/SquareShelf.py')
+md.geometry.bed=md.geometry.bed+50.
+md.geometry.surface=md.geometry.surface+50.
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test226.m
===================================================================
--- /issm/trunk/test/NightlyRun/test226.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test226.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md.timestepping.time_adapt=1.;
+md.timestepping.final_time=10.;
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test226.py
===================================================================
--- /issm/trunk/test/NightlyRun/test226.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test226.py	(revision 13975)
@@ -0,0 +1,44 @@
+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/SquareShelf.py')
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test227.m
===================================================================
--- /issm/trunk/test/NightlyRun/test227.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test227.m	(revision 13975)
@@ -1,16 +1,16 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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);
+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'};
+	'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,...
Index: /issm/trunk/test/NightlyRun/test227.py
===================================================================
--- /issm/trunk/test/NightlyRun/test227.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test227.py	(revision 13975)
@@ -0,0 +1,59 @@
+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/SquareShelf.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test228.m
===================================================================
--- /issm/trunk/test/NightlyRun/test228.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test228.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -5,17 +5,17 @@
 md.cluster=generic('name',oshostname(),'np',3);
 
-md.timestepping.time_step=1;
+md.timestepping.time_step=1.;
 md.settings.output_frequency=1;
-md.timestepping.final_time=4;
+md.timestepping.final_time=4.;
 
 %Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
+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.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
 md.transient.isthermal=0;
 
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -28,5 +28,4 @@
 	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),...
Index: /issm/trunk/test/NightlyRun/test228.py
===================================================================
--- /issm/trunk/test/NightlyRun/test228.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test228.py	(revision 13975)
@@ -0,0 +1,72 @@
+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/SquareShelf.py')
+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=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test229.m
===================================================================
--- /issm/trunk/test/NightlyRun/test229.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test229.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -5,17 +5,17 @@
 md.cluster=generic('name',oshostname(),'np',3);
 
-md.timestepping.time_step=1;
+md.timestepping.time_step=1.;
 md.settings.output_frequency=1;
-md.timestepping.final_time=4;
+md.timestepping.final_time=4.;
 
 %Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*2 ];
+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.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
 md.transient.isthermal=0;
 
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -28,5 +28,4 @@
 	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),...
Index: /issm/trunk/test/NightlyRun/test229.py
===================================================================
--- /issm/trunk/test/NightlyRun/test229.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test229.py	(revision 13975)
@@ -0,0 +1,72 @@
+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/SquareShelf.py')
+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=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*2.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test230.m
===================================================================
--- /issm/trunk/test/NightlyRun/test230.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test230.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',350000);
+md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -11,17 +11,17 @@
 
 %Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*-1 ];
+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.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
 md.transient.isthermal=0;
 
-md=solve(md,TransientSolutionEnum);
+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',...
+	'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,...
@@ -29,5 +29,4 @@
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,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),...
Index: /issm/trunk/test/NightlyRun/test230.py
===================================================================
--- /issm/trunk/test/NightlyRun/test230.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test230.py	(revision 13975)
@@ -0,0 +1,77 @@
+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',350000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*-1.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test231.m
===================================================================
--- /issm/trunk/test/NightlyRun/test231.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test231.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',350000);
+md=triangle(model(),'../Exp/Square.exp',350000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -11,17 +11,17 @@
 
 %Set up transient
-smb = ones(md.mesh.numberofvertices,1)*3.6;
-smb=[ smb smb*2 ];
+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.surfaceforcings.mass_balance=smb;
+md.surfaceforcings.mass_balance(end+1,:)=[1.5 3.];
 md.transient.isthermal=0;
 
-md=solve(md,TransientSolutionEnum);
+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',...
+	'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,...
@@ -29,5 +29,4 @@
 	1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,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),...
Index: /issm/trunk/test/NightlyRun/test231.py
===================================================================
--- /issm/trunk/test/NightlyRun/test231.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test231.py	(revision 13975)
@@ -0,0 +1,77 @@
+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',350000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(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=numpy.ones((md.mesh.numberofvertices,1))*3.6
+smb=numpy.hstack((smb,smb*2.))
+
+md.surfaceforcings.mass_balance=numpy.vstack((smb,[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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test232.m
===================================================================
--- /issm/trunk/test/NightlyRun/test232.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test232.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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.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;
@@ -12,9 +12,9 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+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_tolerances={1e-13,1e-6,1e-13,1e-6,1e-13,1e-6,1e-13,1e-6};
 field_values={...
 	(md.results.TransientSolution(1).Temperature),...
Index: /issm/trunk/test/NightlyRun/test232.py
===================================================================
--- /issm/trunk/test/NightlyRun/test232.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test232.py	(revision 13975)
@@ -0,0 +1,38 @@
+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/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.thermal.spctemperature=numpy.vstack((numpy.hstack((md.thermal.spctemperature, md.thermal.spctemperature+5., md.thermal.spctemperature+10., md.thermal.spctemperature+15.)), [1.5,2.5,3.5,4.]))
+md.timestepping.time_step=1.
+md.timestepping.final_time=4.
+md.transient.isdiagnostic=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-6,1e-13,1e-6,1e-13,1e-6,1e-13,1e-6]
+field_values=[\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	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/test233.m
===================================================================
--- /issm/trunk/test/NightlyRun/test233.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test233.m	(revision 13975)
@@ -1,22 +1,22 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
-md=extrude(md,3,1);
+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.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);
+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'};
+	'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};
+	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),...
Index: /issm/trunk/test/NightlyRun/test233.py
===================================================================
--- /issm/trunk/test/NightlyRun/test233.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test233.py	(revision 13975)
@@ -0,0 +1,72 @@
+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',200000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'pattyn','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.thermal.spctemperature=numpy.vstack((numpy.hstack((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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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/test234.m
===================================================================
--- /issm/trunk/test/NightlyRun/test234.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test234.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -55,5 +55,5 @@
 
 %solve
-md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=solve(md,TransientSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test235.m
===================================================================
--- /issm/trunk/test/NightlyRun/test235.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test235.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelf.par');
@@ -55,5 +55,5 @@
 
 %solve
-md=solve(md,TransientSolutionEnum,'overwrite','y');
+md=solve(md,TransientSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test236.m
===================================================================
--- /issm/trunk/test/NightlyRun/test236.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test236.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 
@@ -12,15 +12,14 @@
 load '../Data/delta18o.data'
 md.surfaceforcings.delta18o=delta18o;
-%  creating delta18oSurface
+% 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;
+% Same temperature over the all region:
+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;
+    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);
@@ -31,5 +30,5 @@
 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;
+itemp=0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
 md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
 
@@ -44,17 +43,16 @@
 % time steps and resolution
 md.timestepping.time_step=20;
-md.timestepping.final_time= 60;
+md.timestepping.final_time=60;
 
 % 
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
-
+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};
+	1e-13,1e-13,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),...
Index: /issm/trunk/test/NightlyRun/test236.py
===================================================================
--- /issm/trunk/test/NightlyRun/test236.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test236.py	(revision 13975)
@@ -0,0 +1,96 @@
+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','')
+
+# Use of ispdd and isdelta18o methods
+md.surfaceforcings.ispdd=1
+md.surfaceforcings.isdelta18o=1
+
+md=parameterize(md,'../Par/SquareShelf.py')
+
+# Add temperature, precipitation and delta18o needed to measure the surface mass balance
+# creating delta18o
+delta18o=numpy.loadtxt('../Data/delta18o.data')
+md.surfaceforcings.delta18o=delta18o
+# creating delta18oSurface
+md.surfaceforcings.delta18o_surface = numpy.zeros((2,numpy.size(delta18o,axis=1)))
+md.surfaceforcings.delta18o_surface[1,:] = delta18o[1,:]
+
+# creating Present day and lgm temperatures
+# Same temperature over the all region:
+tmonth=numpy.ones(12)*(238.15+20.)
+md.surfaceforcings.temperatures_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+md.surfaceforcings.temperatures_lgm=numpy.zeros((md.mesh.numberofvertices+1,12))
+for imonth in xrange(0,12):
+    md.surfaceforcings.temperatures_presentday[0:md.mesh.numberofvertices,imonth]=tmonth[imonth]
+    md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,imonth]=tmonth[imonth]-20.
+    # Time for the last line:
+    md.surfaceforcings.temperatures_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+    md.surfaceforcings.temperatures_lgm[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=numpy.mean(md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,:],axis=1).reshape(-1,1)    #-10*ones(md.mesh.numberofvertices,1)
+md.thermal.spctemperature=numpy.tile(md.thermal.spctemperature,(1,md.timestepping.final_time/md.timestepping.time_step))
+itemp=numpy.arange(0,md.timestepping.final_time,md.timestepping.time_step)
+md.thermal.spctemperature=numpy.vstack((md.thermal.spctemperature,itemp.reshape(1,-1)))
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,0]    #*ones(md.mesh.numberofvertices,1)
+
+# creating precipitation
+md.surfaceforcings.precipitations_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+for imonth in xrange(0,12):
+    md.surfaceforcings.precipitations_presentday[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
+    md.surfaceforcings.precipitations_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# 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())
+
+#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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMonthlytemperatures,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test237.m
===================================================================
--- /issm/trunk/test/NightlyRun/test237.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test237.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',600000);%180000
+md=triangle(model(),'../Exp/Square.exp',600000.);%180000
 md=setmask(md,'all','');
 
@@ -12,15 +12,14 @@
 load '../Data/delta18o.data'
 md.surfaceforcings.delta18o=delta18o;
-%  creating delta18oSurface
+% 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;
+% Same temperature over the all region:
+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;
+    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);
@@ -31,5 +30,5 @@
 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;
+itemp=0:md.timestepping.time_step:md.timestepping.final_time-md.timestepping.time_step;
 md.thermal.spctemperature(md.mesh.numberofvertices+1,:)=itemp;
 
@@ -45,21 +44,20 @@
 md.timestepping.time_step=20;
 md.settings.output_frequency=1;
-md.timestepping.final_time= 60;
+md.timestepping.final_time=60;
 
 %
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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'};
+						'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};
-
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,1e-8,1e-8,1e-13,1e-8,...
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,1e-8,1e-8,1e-13,1e-8,...
+	1e-13,1e-13,1e-08,1e-13,1e-13,1e-8,1e-8,1e-8,1e-13,1e-8};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test237.py
===================================================================
--- /issm/trunk/test/NightlyRun/test237.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test237.py	(revision 13975)
@@ -0,0 +1,110 @@
+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',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.py')
+
+# Add temperature, precipitation and delta18o needed to measure the surface mass balance
+# creating delta18o
+delta18o=numpy.loadtxt('../Data/delta18o.data')
+md.surfaceforcings.delta18o=delta18o
+# creating delta18oSurface
+md.surfaceforcings.delta18o_surface = numpy.zeros((2,numpy.size(delta18o,axis=1)))
+md.surfaceforcings.delta18o_surface[1,:] = delta18o[1,:]
+
+# creating Present day and lgm temperatures
+# Same temperature over the all region:
+tmonth=numpy.ones(12)*(238.15+20.)
+md.surfaceforcings.temperatures_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+md.surfaceforcings.temperatures_lgm=numpy.zeros((md.mesh.numberofvertices+1,12))
+for imonth in xrange(0,12):
+    md.surfaceforcings.temperatures_presentday[0:md.mesh.numberofvertices,imonth]=tmonth[imonth]
+    md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,imonth]=tmonth[imonth]-20.
+    # Time for the last line:
+    md.surfaceforcings.temperatures_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+    md.surfaceforcings.temperatures_lgm[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# creating initialization and spc temperatures initialization and spc
+md.thermal.spctemperature=numpy.mean(md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,:],axis=1).reshape(-1,1)    #-10*ones(md.mesh.numberofvertices,1)
+md.thermal.spctemperature=numpy.tile(md.thermal.spctemperature,(1,md.timestepping.final_time/md.timestepping.time_step))
+itemp=numpy.arange(0,md.timestepping.final_time,md.timestepping.time_step)
+md.thermal.spctemperature=numpy.vstack((md.thermal.spctemperature,itemp.reshape(1,-1)))
+
+md.initialization.temperature=md.surfaceforcings.temperatures_lgm[0:md.mesh.numberofvertices,0]    #*ones(md.mesh.numberofvertices,1)
+
+# creating precipitation
+md.surfaceforcings.precipitations_presentday=numpy.zeros((md.mesh.numberofvertices+1,12))
+for imonth in xrange(0,12):
+    md.surfaceforcings.precipitations_presentday[0:md.mesh.numberofvertices,imonth]=-0.4*10**(-6)*md.mesh.y+0.5
+    md.surfaceforcings.precipitations_presentday[md.mesh.numberofvertices,imonth]=((float(imonth)+1.)/12.)
+
+# time steps and resolution
+md.timestepping.time_step=20.
+md.settings.output_frequency=1
+md.timestepping.final_time=60.
+
+#
+md.extrude(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-8,1e-8,1e-13,1e-13,1e-8,\
+	1e-13,1e-13,1e-13,1e-13,1e-13,1e-8,1e-8,1e-13,1e-13,1e-8,\
+	1e-13,1e-13,1e-08,1e-13,1e-13,1e-8,1e-8,1e-10,1e-13,1e-8]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[0].SurfaceforcingsMonthlytemperatures,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test270.m
===================================================================
--- /issm/trunk/test/NightlyRun/test270.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test270.m	(revision 13975)
@@ -1,12 +1,12 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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_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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test270.py
===================================================================
--- /issm/trunk/test/NightlyRun/test270.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test270.py	(revision 13975)
@@ -0,0 +1,32 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from matdamageice import *
+from paterson 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/SquareShelf.py')
+md.materials=matdamageice()
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md=setflowequation(md,'macayeal','all')
+md.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/test272.m
===================================================================
--- /issm/trunk/test/NightlyRun/test272.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test272.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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_n=3.*ones(md.mesh.numberofelements,1);
 md.materials.rheology_Z=0.5*ones(md.mesh.numberofvertices,1);
 md=setflowequation(md,'macayeal','all');
@@ -14,8 +14,8 @@
 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=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.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; 
@@ -23,12 +23,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyZbar' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
    (md.results.DiagnosticSolution.MaterialsRheologyZbar),...
    (md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test272.py
===================================================================
--- /issm/trunk/test/NightlyRun/test272.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test272.py	(revision 13975)
@@ -0,0 +1,50 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from matdamageice import *
+from paterson 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/SquareShelf.py')
+md.materials=matdamageice()
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md=setflowequation(md,'macayeal','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['MaterialsRheologyZbar']
+md.inversion.min_parameters=10**-13*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=101.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.gradient_scaling=0.9*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test274.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000);
+md=triangle(model(),'../Exp/SquareHole.exp','../Exp/Rifts.exp',50000.);
 md=meshprocessrifts(md,'../Exp/Square.exp');
 md=setmask(md,'all','');
@@ -5,10 +5,10 @@
 md.materials=matdamageice();
 md.materials.rheology_B=paterson(md.initialization.temperature);
-md.materials.rheology_n=3*ones(md.mesh.numberofelements,1);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test274.py
===================================================================
--- /issm/trunk/test/NightlyRun/test274.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test274.py	(revision 13975)
@@ -0,0 +1,35 @@
+import numpy
+from model import *
+from triangle import *
+from meshprocessrifts import *
+from setmask import *
+from parameterize import *
+from matdamageice import *
+from paterson import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+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.py')
+md.materials=matdamageice()
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+md.materials.rheology_Z=0.5*numpy.ones((md.mesh.numberofvertices,1))
+md=setflowequation(md,'macayeal','all')
+
+md.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 13974)
+++ /issm/trunk/test/NightlyRun/test3001.m	(revision 13975)
@@ -1,10 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',50000);
+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.diagnostic.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
-md=solve(md,DiagnosticSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3001.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3001.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3001.py	(revision 13975)
@@ -0,0 +1,32 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+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.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 13974)
+++ /issm/trunk/test/NightlyRun/test3002.m	(revision 13975)
@@ -1,10 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+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);
+md.verbose=verbose('autodiff',true);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3002.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3002.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3002.py	(revision 13975)
@@ -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,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 13974)
+++ /issm/trunk/test/NightlyRun/test3003.m	(revision 13975)
@@ -1,11 +1,12 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.diagnostic.requested_outputs=StressTensorEnum;
+md.diagnostic.requested_outputs=StressTensorEnum();
 md.autodiff.isautodiff=true;
-md=solve(md,DiagnosticSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3003.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3003.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3003.py	(revision 13975)
@@ -0,0 +1,37 @@
+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.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 13974)
+++ /issm/trunk/test/NightlyRun/test3004.m	(revision 13975)
@@ -1,10 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,2);
+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);
+md.verbose=verbose('autodiff',true);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3004.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3004.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3004.py	(revision 13975)
@@ -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,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 13974)
+++ /issm/trunk/test/NightlyRun/test3005.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
@@ -5,5 +5,6 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.autodiff.isautodiff=true;
-md=solve(md,PrognosticSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3005.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3005.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3005.py	(revision 13975)
@@ -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.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 13974)
+++ /issm/trunk/test/NightlyRun/test3006.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
 md=setmask(md,'all','');
@@ -8,5 +8,6 @@
 md.prognostic.spcthickness=md.geometry.thickness;
 md.autodiff.isautodiff=true;
-md=solve(md,PrognosticSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3006.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3006.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3006.py	(revision 13975)
@@ -0,0 +1,27 @@
+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.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 13974)
+++ /issm/trunk/test/NightlyRun/test3007.m	(revision 13975)
@@ -1,10 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,5,3.);
 md.cluster=generic('name',oshostname(),'np',3);
 md.autodiff.isautodiff=true;
-md=solve(md,PrognosticSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3007.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3007.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3007.py	(revision 13975)
@@ -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=setflowequation(md,'macayeal','all')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test3008.m	(revision 13975)
@@ -1,11 +1,12 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+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);
+md.verbose=verbose('autodiff',true);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3008.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3008.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3008.py	(revision 13975)
@@ -0,0 +1,26 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/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.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 13974)
+++ /issm/trunk/test/NightlyRun/test3009.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -10,5 +10,6 @@
 md.transient.isgroundingline=0;
 md.autodiff.isautodiff=true;
-md=solve(md,TransientSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3009.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3009.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3009.py	(revision 13975)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+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.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[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test301.m
===================================================================
--- /issm/trunk/test/NightlyRun/test301.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test301.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test301.py
===================================================================
--- /issm/trunk/test/NightlyRun/test301.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test301.py	(revision 13975)
@@ -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',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+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 13974)
+++ /issm/trunk/test/NightlyRun/test3010.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'all','');
 md=parameterize(md,'../Par/SquareShelfConstrained.par');
@@ -7,5 +7,6 @@
 
 md.autodiff.isautodiff=true;
-md=solve(md,TransientSolutionEnum);
+md.verbose=verbose('autodiff',true);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test3010.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3010.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3010.py	(revision 13975)
@@ -0,0 +1,50 @@
+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.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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].IceVolume,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test3015.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.m	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3015.m	(revision 13975)
@@ -0,0 +1,77 @@
+%This test runs test3005 with autodiff on, and checks that 
+%the value of the scalar forward difference match a step-wise differential
+
+%First configure
+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.prognostic.requested_outputs=IceVolumeEnum();
+md.verbose=verbose('autodiff',true);
+
+%setup autodiff parameters
+index=1; %this is the scalar component we are checking against
+md.autodiff.independents={...
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
+	};
+
+md.autodiff.dependents={...
+	dependent('name','IceVolume','type','scalar')...
+	};
+md.autodiff.driver='fos_forward';
+
+%parameters for the step-wise derivative
+delta=0.001;
+h1=md.geometry.thickness(index);
+h0=h1*(1.-delta);
+h2=h1*(1.+delta);
+deltaH=(h2-h0);
+
+%save model:
+md2=md;
+
+%evaluate derivative by forward and backward stepping 
+%forward
+md=md2;
+md.autodiff.isautodiff=false;
+md.geometry.thickness(index)=h0;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,PrognosticSolutionEnum());
+V0=md.results.PrognosticSolution.IceVolume;
+
+%backward
+md=md2;
+md.autodiff.isautodiff=false;
+md.geometry.thickness(index)=h2;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,PrognosticSolutionEnum());
+V2=md.results.PrognosticSolution.IceVolume;
+
+%compute resulting derivative
+dVdh_an=(V2-V0)/deltaH;
+
+%evaluate derivative using ADOLC 
+md=md2;
+md.autodiff.isautodiff=true;
+md.geometry.thickness(index)=h1;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,PrognosticSolutionEnum());
+%retrieve directly
+dVdh_ad=md.results.PrognosticSolution.AutodiffJacobian;
+
+disp(sprintf('dV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n',dVdh_an,dVdh_ad));
+
+%Fields and tolerances to track changes
+field_names     ={'dV/dh-dV/dh0'};
+field_tolerances={1e-13};
+field_values={dVdh_ad-dVdh_an};
Index: /issm/trunk/test/NightlyRun/test3015.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3015.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3015.py	(revision 13975)
@@ -0,0 +1,91 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from independent import *
+from dependent import *
+from SetIceShelfBC import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#This test runs test3005 with autodiff on, and checks that 
+#the value of the scalar forward difference match a step-wise differential
+
+#First configure
+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.prognostic.requested_outputs=IceVolumeEnum()
+md.verbose=verbose('autodiff',True)
+
+#setup autodiff parameters
+index=1 #this is the scalar component we are checking against
+md.autodiff.independents=[\
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
+	]
+
+md.autodiff.dependents=[\
+	dependent('name','IceVolume','type','scalar')\
+	]
+md.autodiff.driver='fos_forward'
+
+#parameters for the step-wise derivative
+delta=0.001
+h1=md.geometry.thickness[index]
+h0=h1*(1.-delta)
+h2=h1*(1.+delta)
+deltaH=(h2-h0)
+
+#save model
+md2=copy.deepcopy(md)
+
+#evaluate derivative by forward and backward stepping 
+#forward
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=False
+md.geometry.thickness[index]=h0
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,PrognosticSolutionEnum())
+V0=md.results.PrognosticSolution.IceVolume
+
+#backward
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=False
+md.geometry.thickness[index]=h2
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,PrognosticSolutionEnum())
+V2=md.results.PrognosticSolution.IceVolume
+
+#compute resulting derivative
+dVdh_an=(V2-V0)/deltaH
+
+#evaluate derivative using ADOLC 
+md=md2
+md.autodiff.isautodiff=True
+md.geometry.thickness[index]=h1
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,PrognosticSolutionEnum())
+#retrieve directly
+dVdh_ad=md.results.PrognosticSolution.AutodiffJacobian
+
+print "dV/dh: analytical:  #16.16g\n       using adolc:  #16.16g\n" % (dVdh_an,dVdh_ad)
+
+#Fields and tolerances to track changes
+field_names     =['dV/dh-dV/dh0']
+field_tolerances=[1e-13]
+field_values=[dVdh_ad-dVdh_an]
Index: /issm/trunk/test/NightlyRun/test3019.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.m	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3019.m	(revision 13975)
@@ -0,0 +1,34 @@
+%test reverse scalar vs forward vectorial drivers in ADOLC, using the test3009 setup, equivalent to test109 setup.
+md=triangle(model(),'../Exp/Square.exp',100000.);
+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.verbose.autodiff=true;
+
+%first run scalar reverse mode: 
+md.autodiff.independents={independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices)};
+md.autodiff.dependents={dependent('name','MaxVel','type','scalar','fos_reverse_index',1)};
+md.autodiff.driver='fos_reverse';
+
+md=solve(md,TransientSolutionEnum());
+
+%recover jacobian: 
+jac_reverse=md.results.TransientSolution(1).AutodiffJacobian;
+
+%now run vectorial forward mode
+md.autodiff.independents={independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fov_forward_indices',(1:md.mesh.numberofvertices)')};
+md.autodiff.dependents={dependent('name','MaxVel','type','scalar')};
+md.autodiff.driver='fov_forward';
+
+md=solve(md,TransientSolutionEnum());
+
+%recover jacobian: 
+jac_forward=md.results.TransientSolution(1).AutodiffJacobian;
+
+%Fields and tolerances to track changes
+field_names     ={'Jac Forward','Jac Reverse','Jac Forward - Reverse'};
+field_tolerances={1e-13,1e-13,1e-13};
+field_values={jac_forward,jac_reverse,jac_forward-jac_reverse};
Index: /issm/trunk/test/NightlyRun/test3019.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3019.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3019.py	(revision 13975)
@@ -0,0 +1,46 @@
+import numpy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from independent import *
+from dependent import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#test reverse scalar vs forward vectorial drivers in ADOLC, using the test3009 setup, equivalent to test109 setup.
+md=triangle(model(),'../Exp/Square.exp',100000.)
+md=setmask(md,'all','')
+md=parameterize(md,'../Par/SquareShelfConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+
+md.autodiff.isautodiff=True
+md.verbose.autodiff=True
+
+#first run scalar reverse mode: 
+md.autodiff.independents=[independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices)]
+md.autodiff.dependents=[dependent('name','MaxVel','type','scalar','fos_reverse_index',1)]
+md.autodiff.driver='fos_reverse'
+
+md=solve(md,TransientSolutionEnum())
+
+#recover jacobian: 
+jac_reverse=md.results.TransientSolution[0].AutodiffJacobian
+
+#now run vectorial forward mode
+md.autodiff.independents=[independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fov_forward_indices',numpy.arange(0,md.mesh.numberofvertices))]
+md.autodiff.dependents=[dependent('name','MaxVel','type','scalar')]
+md.autodiff.driver='fov_forward'
+
+md=solve(md,TransientSolutionEnum())
+
+#recover jacobian: 
+jac_forward=md.results.TransientSolution[0].AutodiffJacobian
+
+#Fields and tolerances to track changes
+field_names     =['Jac Forward','Jac Reverse','Jac Forward - Reverse']
+field_tolerances=[1e-13,1e-13,1e-13]
+field_values=[jac_forward,jac_reverse,jac_forward-jac_reverse]
Index: /issm/trunk/test/NightlyRun/test302.m
===================================================================
--- /issm/trunk/test/NightlyRun/test302.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test302.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test302.py
===================================================================
--- /issm/trunk/test/NightlyRun/test302.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test302.py	(revision 13975)
@@ -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',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+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','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/test3020.m
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.m	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3020.m	(revision 13975)
@@ -0,0 +1,84 @@
+%This test runs test3020 with autodiff on, and checks that 
+%the value of the scalar forward difference match a step-wise differential
+
+%First configure
+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();MaxVelEnum()];
+md.verbose=verbose('autodiff',true);
+md.diagnostic.restol=0.000001;
+
+%setup autodiff parameters
+index=1; %this is the scalar component we are checking against
+md.autodiff.independents={...
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
+	};
+
+md.autodiff.dependents={...
+	dependent('name','IceVolume','type','scalar'),...
+	dependent('name','MaxVel','type','scalar')...
+	};
+md.autodiff.driver='fos_forward';
+
+%parameters for the step-wise derivative
+delta=0.00001;
+h1=md.geometry.thickness(index);
+h0=h1*(1.-delta);
+h2=h1*(1.+delta);
+deltaH=(h2-h0);
+
+%save model:
+md2=md;
+
+%evaluate derivative by forward and backward stepping 
+%forward
+md=md2;
+md.autodiff.isautodiff=false;
+md.geometry.thickness(index)=h0;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,TransientSolutionEnum());
+V0=md.results.TransientSolution(end).IceVolume;
+MaxV0=md.results.TransientSolution(end).MaxVel;
+
+%backward
+md=md2;
+md.autodiff.isautodiff=false;
+md.geometry.thickness(index)=h2;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,TransientSolutionEnum());
+V2=md.results.TransientSolution(end).IceVolume;
+MaxV2=md.results.TransientSolution(end).MaxVel;
+
+%compute resulting derivative
+dVdh_an=(V2-V0)/deltaH;
+dMaxVdh_an=(MaxV2-MaxV0)/deltaH;
+
+%evaluate derivative using ADOLC 
+md=md2;
+md.autodiff.isautodiff=true;
+md.geometry.thickness(index)=h1;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
+md.geometry.surface=md.geometry.bed+md.geometry.thickness;
+md=SetIceShelfBC(md);
+
+md=solve(md,TransientSolutionEnum());
+%retrieve directly
+dVdh_ad=md.results.TransientSolution(1).AutodiffJacobian(1);
+dMaxVdh_ad=md.results.TransientSolution(1).AutodiffJacobian(2);
+
+disp(sprintf('dV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n',dVdh_an,dVdh_ad));
+disp(sprintf('dMaxV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n',dMaxVdh_an,dMaxVdh_ad));
+
+%Fields and tolerances to track changes
+field_names     ={'dV/dh-dV/dh0','dMaxV/dh-dMaxV/dh0'};
+field_tolerances={1e-13,1e-13};
+field_values={dVdh_ad-dVdh_an,dMaxVdh_an-dMaxVdh_ad};
Index: /issm/trunk/test/NightlyRun/test3020.py
===================================================================
--- /issm/trunk/test/NightlyRun/test3020.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test3020.py	(revision 13975)
@@ -0,0 +1,98 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from independent import *
+from dependent import *
+from SetIceShelfBC import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+#This test runs test3020 with autodiff on, and checks that 
+#the value of the scalar forward difference match a step-wise differential
+
+#First configure
+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(),MaxVelEnum()]
+md.verbose=verbose('autodiff',True)
+md.diagnostic.restol=0.000001
+
+#setup autodiff parameters
+index=1 #this is the scalar component we are checking against
+md.autodiff.independents=[\
+	independent('name','Thickness','type','vertex','nods',md.mesh.numberofvertices,'fos_forward_index',index)
+	]
+
+md.autodiff.dependents=[\
+	dependent('name','IceVolume','type','scalar'),\
+	dependent('name','MaxVel','type','scalar')\
+	]
+md.autodiff.driver='fos_forward'
+
+#parameters for the step-wise derivative
+delta=0.00001
+h1=md.geometry.thickness[index]
+h0=h1*(1.-delta)
+h2=h1*(1.+delta)
+deltaH=(h2-h0)
+
+#save model:
+md2=copy.deepcopy(md)
+
+#evaluate derivative by forward and backward stepping 
+#forward
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=False
+md.geometry.thickness[index]=h0
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,TransientSolutionEnum())
+V0=md.results.TransientSolution[2].IceVolume
+MaxV0=md.results.TransientSolution[2].MaxVel
+
+#backward
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=False
+md.geometry.thickness[index]=h2
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,TransientSolutionEnum())
+V2=md.results.TransientSolution[2].IceVolume
+MaxV2=md.results.TransientSolution[2].MaxVel
+
+#compute resulting derivative
+dVdh_an=(V2-V0)/deltaH
+dMaxVdh_an=(MaxV2-MaxV0)/deltaH
+
+#evaluate derivative using ADOLC 
+md=copy.deepcopy(md2)
+md.autodiff.isautodiff=True
+md.geometry.thickness[index]=h1
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=SetIceShelfBC(md)
+
+md=solve(md,TransientSolutionEnum())
+#retrieve directly
+dVdh_ad=md.results.TransientSolution[0].AutodiffJacobian[0]
+dMaxVdh_ad=md.results.TransientSolution[0].AutodiffJacobian[1]
+
+print "dV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n" % (dVdh_an,dVdh_ad)
+print "dMaxV/dh: analytical:  %16.16g\n       using adolc:  %16.16g\n" % (dMaxVdh_an,dMaxVdh_ad)
+
+#Fields and tolerances to track changes
+field_names     =['dV/dh-dV/dh0','dMaxV/dh-dMaxV/dh0']
+field_tolerances=[1e-13,1e-13]
+field_values=[dVdh_ad-dVdh_an,dMaxVdh_an-dMaxVdh_ad]
Index: /issm/trunk/test/NightlyRun/test303.m
===================================================================
--- /issm/trunk/test/NightlyRun/test303.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test303.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test303.py
===================================================================
--- /issm/trunk/test/NightlyRun/test303.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test303.py	(revision 13975)
@@ -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',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+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 13974)
+++ /issm/trunk/test/NightlyRun/test304.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,2);
+md=extrude(md,3,2.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test304.py
===================================================================
--- /issm/trunk/test/NightlyRun/test304.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test304.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.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','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 13974)
+++ /issm/trunk/test/NightlyRun/test305.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,5,2);
+md=extrude(md,5,2.);
 md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test305.py
===================================================================
--- /issm/trunk/test/NightlyRun/test305.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test305.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test306.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,4,2);
+md=extrude(md,4,2.);
 md=setflowequation(md,'hutter','../Exp/SquareHalfRight.exp','fill','macayeal');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test306.py
===================================================================
--- /issm/trunk/test/NightlyRun/test306.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test306.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(4,2.)
+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','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 13974)
+++ /issm/trunk/test/NightlyRun/test307.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test307.py
===================================================================
--- /issm/trunk/test/NightlyRun/test307.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test307.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test308.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test308.py
===================================================================
--- /issm/trunk/test/NightlyRun/test308.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test308.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+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/test309.m
===================================================================
--- /issm/trunk/test/NightlyRun/test309.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test309.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test309.py
===================================================================
--- /issm/trunk/test/NightlyRun/test309.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test309.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.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.Thickness,\
+	]
Index: /issm/trunk/test/NightlyRun/test310.m
===================================================================
--- /issm/trunk/test/NightlyRun/test310.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test310.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=meshconvert(md);
 md=setmask(md,'','');
@@ -7,5 +7,5 @@
 md.prognostic.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test310.py
===================================================================
--- /issm/trunk/test/NightlyRun/test310.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test310.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+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())
+
+#Fields and tolerances to track changes
+field_names     =['Thickness']
+field_tolerances=[1e-13]
+field_values=[\
+	md.results.PrognosticSolution.Thickness,\
+	]
Index: /issm/trunk/test/NightlyRun/test311.m
===================================================================
--- /issm/trunk/test/NightlyRun/test311.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test311.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -5,5 +5,5 @@
 md=extrude(md,5,0.5);
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test311.py
===================================================================
--- /issm/trunk/test/NightlyRun/test311.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test311.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test312.m	(revision 13975)
@@ -1,14 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
+md.timestepping.time_step=0.;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_tolerances={1e-13,1e-8};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
Index: /issm/trunk/test/NightlyRun/test312.py
===================================================================
--- /issm/trunk/test/NightlyRun/test312.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test312.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.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-8]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test313.m
===================================================================
--- /issm/trunk/test/NightlyRun/test313.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test313.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -10,5 +10,5 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test313.py
===================================================================
--- /issm/trunk/test/NightlyRun/test313.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test313.py	(revision 13975)
@@ -0,0 +1,29 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test314.m
===================================================================
--- /issm/trunk/test/NightlyRun/test314.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test314.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
 md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test314.py
===================================================================
--- /issm/trunk/test/NightlyRun/test314.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test314.py	(revision 13975)
@@ -0,0 +1,42 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'hutter','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-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.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test315.m
===================================================================
--- /issm/trunk/test/NightlyRun/test315.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test315.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -5,13 +5,13 @@
 md=setflowequation(md,'hutter','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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_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),...
Index: /issm/trunk/test/NightlyRun/test315.py
===================================================================
--- /issm/trunk/test/NightlyRun/test315.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test315.py	(revision 13975)
@@ -0,0 +1,56 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test316.m
===================================================================
--- /issm/trunk/test/NightlyRun/test316.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test316.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test316.py
===================================================================
--- /issm/trunk/test/NightlyRun/test316.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test316.py	(revision 13975)
@@ -0,0 +1,42 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md=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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test317.m
===================================================================
--- /issm/trunk/test/NightlyRun/test317.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test317.m	(revision 13975)
@@ -1,17 +1,17 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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','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};
+	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),...
Index: /issm/trunk/test/NightlyRun/test317.py
===================================================================
--- /issm/trunk/test/NightlyRun/test317.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test317.py	(revision 13975)
@@ -0,0 +1,56 @@
+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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test318.m
===================================================================
--- /issm/trunk/test/NightlyRun/test318.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test318.m	(revision 13975)
@@ -1,15 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,4,1);
+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);
+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_tolerances={1e-13,1e-13,1e-10,1e-10,1e-13,1e-11,1e-6};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test318.py
===================================================================
--- /issm/trunk/test/NightlyRun/test318.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test318.py	(revision 13975)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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-10,1e-10,1e-13,1e-11,1e-6]
+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/test319.m
===================================================================
--- /issm/trunk/test/NightlyRun/test319.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test319.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -7,10 +7,10 @@
 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.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.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);
@@ -18,12 +18,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.FrictionCoefficient),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test319.py
===================================================================
--- /issm/trunk/test/NightlyRun/test319.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test319.py	(revision 13975)
@@ -0,0 +1,45 @@
+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',200000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'macayeal','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones(md.inversion.nsteps)
+md.inversion.step_threshold=0.3*numpy.ones(md.inversion.nsteps)
+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 13974)
+++ /issm/trunk/test/NightlyRun/test320.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 
@@ -8,10 +8,10 @@
 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.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.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);
@@ -19,12 +19,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.FrictionCoefficient),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test320.py
===================================================================
--- /issm/trunk/test/NightlyRun/test320.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test320.py	(revision 13975)
@@ -0,0 +1,46 @@
+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',200000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'macayeal','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones(md.inversion.nsteps)
+md.inversion.step_threshold=0.3*numpy.ones(md.inversion.nsteps)
+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: /issm/trunk/test/NightlyRun/test321.m
===================================================================
--- /issm/trunk/test/NightlyRun/test321.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test321.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 
@@ -8,10 +8,10 @@
 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.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.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);
@@ -19,12 +19,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.FrictionCoefficient),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test321.py
===================================================================
--- /issm/trunk/test/NightlyRun/test321.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test321.py	(revision 13975)
@@ -0,0 +1,46 @@
+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',200000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'pattyn','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((102*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones(md.inversion.nsteps)
+md.inversion.step_threshold=0.3*numpy.ones(md.inversion.nsteps)
+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 13974)
+++ /issm/trunk/test/NightlyRun/test322.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'stokes','all');
 
@@ -8,10 +8,10 @@
 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.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.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);
@@ -19,12 +19,12 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.FrictionCoefficient),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test322.py
===================================================================
--- /issm/trunk/test/NightlyRun/test322.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test322.py	(revision 13975)
@@ -0,0 +1,46 @@
+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',200000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'stokes','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((104*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones(md.inversion.nsteps)
+md.inversion.step_threshold=0.3*numpy.ones(md.inversion.nsteps)
+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: /issm/trunk/test/NightlyRun/test323.m
===================================================================
--- /issm/trunk/test/NightlyRun/test323.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test323.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -5,6 +5,6 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1;
-md.timestepping.final_time=600;
-md=solve(md,TransientSolutionEnum);
+md.timestepping.final_time=600.;
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test323.py
===================================================================
--- /issm/trunk/test/NightlyRun/test323.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test323.py	(revision 13975)
@@ -0,0 +1,45 @@
+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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test324.m
===================================================================
--- /issm/trunk/test/NightlyRun/test324.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test324.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -6,14 +6,14 @@
 md.cluster=generic('name',oshostname(),'np',3);
 md.timestepping.time_adapt=1;
-md.timestepping.final_time=500;
-md=solve(md,TransientSolutionEnum);
+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_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};
+	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),...
Index: /issm/trunk/test/NightlyRun/test324.py
===================================================================
--- /issm/trunk/test/NightlyRun/test324.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test324.py	(revision 13975)
@@ -0,0 +1,59 @@
+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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test325.m
===================================================================
--- /issm/trunk/test/NightlyRun/test325.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test325.m	(revision 13975)
@@ -1,11 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
-md.timestepping.time_step=0;
+md.timestepping.time_step=0.;
 md.cluster=generic('name',oshostname(),'np',3);
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,EnthalpySolutionEnum);
+md=solve(md,EnthalpySolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test325.py
===================================================================
--- /issm/trunk/test/NightlyRun/test325.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test325.py	(revision 13975)
@@ -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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.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,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 13974)
+++ /issm/trunk/test/NightlyRun/test326.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+md=triangle(model(),'../Exp/Square.exp',180000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -11,5 +11,5 @@
 md.transient.isgroundingline=0;
 md.thermal.isenthalpy=1;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test326.py
===================================================================
--- /issm/trunk/test/NightlyRun/test326.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test326.py	(revision 13975)
@@ -0,0 +1,40 @@
+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,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.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,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[0].Enthalpy,\
+	md.results.TransientSolution[0].Waterfraction,\
+	md.results.TransientSolution[0].Temperature,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test327.m
===================================================================
--- /issm/trunk/test/NightlyRun/test327.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test327.m	(revision 13975)
@@ -1,22 +1,22 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+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.initialization.temperature(:)=272.;
+md.thermal.spctemperature(find(md.mesh.vertexonsurface))=272.;
 md.thermal.isenthalpy=1;
-md.basalforcings.geothermalflux(:)=5;
-md=solve(md,TransientSolutionEnum);
+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_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};
+	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),...
Index: /issm/trunk/test/NightlyRun/test327.py
===================================================================
--- /issm/trunk/test/NightlyRun/test327.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test327.py	(revision 13975)
@@ -0,0 +1,65 @@
+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',200000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(3,1.)
+md=setflowequation(md,'pattyn','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.initialization.waterfraction=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.temperature[:]=272.
+md.thermal.spctemperature[numpy.nonzero(md.mesh.vertexonsurface)[0]]=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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].Enthalpy,\
+	md.results.TransientSolution[0].Waterfraction,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test328.m
===================================================================
--- /issm/trunk/test/NightlyRun/test328.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test328.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
@@ -12,6 +12,15 @@
 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.surfaceforcings.href=md.geometry.surface;
+for i=1:size(md.surfaceforcings.hc),
+	if md.geometry.surface(i)<md.surfaceforcings.hc(i)
+		smbref(i)=md.surfaceforcings.a_neg(i)+md.surfaceforcings.b_neg(i)*md.geometry.surface(i);
+	else
+		smbref(i)=md.surfaceforcings.a_pos(i)+md.surfaceforcings.b_pos(i)*md.geometry.surface(i);
+	end
+end
+md.surfaceforcings.smbref=smbref';
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test328.py
===================================================================
--- /issm/trunk/test/NightlyRun/test328.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test328.py	(revision 13975)
@@ -0,0 +1,64 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md=setflowequation(md,'macayeal','all')
+md.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.surfaceforcings.href=copy.deepcopy(md.geometry.surface).reshape(-1)
+smbref=numpy.empty_like(md.surfaceforcings.hc)
+for i in xrange(numpy.size(md.surfaceforcings.hc,axis=0)):
+	if md.geometry.surface[i]<md.surfaceforcings.hc[i]:
+		smbref[i]=md.surfaceforcings.a_neg[i]+md.surfaceforcings.b_neg[i]*md.geometry.surface[i]
+	else:
+		smbref[i]=md.surfaceforcings.a_pos[i]+md.surfaceforcings.b_pos[i]*md.geometry.surface[i]
+md.surfaceforcings.smbref=smbref
+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','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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[0].TotalSmb,\
+	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].TotalSmb,\
+	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[2].TotalSmb,\
+	]
Index: /issm/trunk/test/NightlyRun/test329.m
===================================================================
--- /issm/trunk/test/NightlyRun/test329.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test329.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'','');
 md=parameterize(md,'../Par/SquareSheetConstrained.par');
-md=extrude(md,3,1);
+md=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.surfaceforcings.issmbgradients=1;
@@ -12,14 +12,22 @@
 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.surfaceforcings.href=md.geometry.surface;
+for i=1:size(md.surfaceforcings.hc),
+	if md.geometry.surface(i)<md.surfaceforcings.hc(i)
+		smbref(i)=md.surfaceforcings.a_neg(i)+md.surfaceforcings.b_neg(i)*md.geometry.surface(i);
+	else
+		smbref(i)=md.surfaceforcings.a_pos(i)+md.surfaceforcings.b_pos(i)*md.geometry.surface(i);
+	end
+end
+md.surfaceforcings.smbref=smbref';
 md.transient.requested_outputs=TotalSmbEnum();
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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};
-
+	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),...
Index: /issm/trunk/test/NightlyRun/test329.py
===================================================================
--- /issm/trunk/test/NightlyRun/test329.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test329.py	(revision 13975)
@@ -0,0 +1,73 @@
+import numpy
+import copy
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'','')
+md=parameterize(md,'../Par/SquareSheetConstrained.py')
+md.extrude(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.surfaceforcings.href=copy.deepcopy(md.geometry.surface).reshape(-1)
+smbref=numpy.empty_like(md.surfaceforcings.hc)
+for i in xrange(numpy.size(md.surfaceforcings.hc,axis=0)):
+	if md.geometry.surface[i]<md.surfaceforcings.hc[i]:
+		smbref[i]=md.surfaceforcings.a_neg[i]+md.surfaceforcings.b_neg[i]*md.geometry.surface[i]
+	else:
+		smbref[i]=md.surfaceforcings.a_pos[i]+md.surfaceforcings.b_pos[i]*md.geometry.surface[i]
+md.surfaceforcings.smbref=smbref
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].SurfaceforcingsMassBalance,\
+	md.results.TransientSolution[0].TotalSmb,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test401.m
===================================================================
--- /issm/trunk/test/NightlyRun/test401.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test401.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test401.py
===================================================================
--- /issm/trunk/test/NightlyRun/test401.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test401.py	(revision 13975)
@@ -0,0 +1,26 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'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 13974)
+++ /issm/trunk/test/NightlyRun/test402.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,4,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test402.py
===================================================================
--- /issm/trunk/test/NightlyRun/test402.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test402.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(4,1.)
+md=setflowequation(md,'macayeal','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/test403.m
===================================================================
--- /issm/trunk/test/NightlyRun/test403.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test403.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=extrude(md,5,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test403.py
===================================================================
--- /issm/trunk/test/NightlyRun/test403.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test403.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test404.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test404.py
===================================================================
--- /issm/trunk/test/NightlyRun/test404.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test404.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,1.)
+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-07,1e-07,1e-06,1e-07,1e-07]
+field_values=[\
+	md.results.DiagnosticSolution.Vx,\
+	md.results.DiagnosticSolution.Vy,\
+	md.results.DiagnosticSolution.Vz,\
+	md.results.DiagnosticSolution.Vel,\
+	md.results.DiagnosticSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test405.m
===================================================================
--- /issm/trunk/test/NightlyRun/test405.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test405.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test405.py
===================================================================
--- /issm/trunk/test/NightlyRun/test405.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test405.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test406.m	(revision 13975)
@@ -1,14 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,4,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,ThermalSolutionEnum);
+md.timestepping.time_step=0.;
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
 field_names     ={'Temperature','BasalforcingsMeltingRate'};
-field_tolerances={1e-13,1e-13};
+field_tolerances={1e-13,1e-5};
 field_values={...
 	(md.results.ThermalSolution.Temperature),...
Index: /issm/trunk/test/NightlyRun/test406.py
===================================================================
--- /issm/trunk/test/NightlyRun/test406.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test406.py	(revision 13975)
@@ -0,0 +1,26 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(4,1.)
+md=setflowequation(md,'pattyn','all')
+md.cluster=generic('name',oshostname(),'np',3)
+md.timestepping.time_step=0.
+md=solve(md,ThermalSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Temperature','BasalforcingsMeltingRate']
+field_tolerances=[1e-13,1e-5]
+field_values=[\
+	md.results.ThermalSolution.Temperature,\
+	md.results.ThermalSolution.BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test407.m
===================================================================
--- /issm/trunk/test/NightlyRun/test407.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test407.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,4,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
@@ -9,5 +9,5 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test407.py
===================================================================
--- /issm/trunk/test/NightlyRun/test407.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test407.py	(revision 13975)
@@ -0,0 +1,29 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(4,1.)
+md=setflowequation(md,'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[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test408.m
===================================================================
--- /issm/trunk/test/NightlyRun/test408.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test408.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test408.py
===================================================================
--- /issm/trunk/test/NightlyRun/test408.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test408.py	(revision 13975)
@@ -0,0 +1,43 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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[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/test409.m
===================================================================
--- /issm/trunk/test/NightlyRun/test409.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test409.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=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);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test409.py
===================================================================
--- /issm/trunk/test/NightlyRun/test409.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test409.py	(revision 13975)
@@ -0,0 +1,58 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test410.m
===================================================================
--- /issm/trunk/test/NightlyRun/test410.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test410.m	(revision 13975)
@@ -1,14 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=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);
+md=solve(md,SteadystateSolutionEnum());
 
 %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_tolerances={1e-09,1e-09,1e-09,1e-10,1e-13,1e-10,1e-06};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test410.py
===================================================================
--- /issm/trunk/test/NightlyRun/test410.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test410.py	(revision 13975)
@@ -0,0 +1,31 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,2.)
+md=setflowequation(md,'macayeal','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-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,\
+	]
Index: /issm/trunk/test/NightlyRun/test411.m
===================================================================
--- /issm/trunk/test/NightlyRun/test411.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test411.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=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);
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test411.py
===================================================================
--- /issm/trunk/test/NightlyRun/test411.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test411.py	(revision 13975)
@@ -0,0 +1,32 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test412.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',300000);
+md=triangle(model(),'../Exp/Square.exp',300000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -33,5 +33,5 @@
 
 %solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test413.m
===================================================================
--- /issm/trunk/test/NightlyRun/test413.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test413.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -34,5 +34,5 @@
 
 %solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test414.m
===================================================================
--- /issm/trunk/test/NightlyRun/test414.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test414.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -48,5 +48,5 @@
 
 %solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test415.m
===================================================================
--- /issm/trunk/test/NightlyRun/test415.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test415.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',170000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 
@@ -8,21 +8,21 @@
 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.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.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.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);
+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_names     ={'Gradient','Misfits','FrictionCoefficient','Pressure','Vel','Vx','Vy','Vz','Temperature','BasalforcingsMeltingRate'};
+field_tolerances={1e-10,1e-9,1e-10,1e-13,1e-10,1e-09,1e-10,1e-8,1e-09,1e-6};
 field_values={...
 	(md.results.SteadystateSolution.Gradient1),...
Index: /issm/trunk/test/NightlyRun/test415.py
===================================================================
--- /issm/trunk/test/NightlyRun/test415.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test415.py	(revision 13975)
@@ -0,0 +1,50 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',170000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'macayeal','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.3*numpy.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-9,1e-10,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 13974)
+++ /issm/trunk/test/NightlyRun/test416.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Square.exp',170000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 
@@ -8,20 +8,20 @@
 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.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.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.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);
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+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={...
Index: /issm/trunk/test/NightlyRun/test416.py
===================================================================
--- /issm/trunk/test/NightlyRun/test416.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test416.py	(revision 13975)
@@ -0,0 +1,50 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',170000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'pattyn','all')
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((102*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.3*numpy.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-08,1e-07,1e-08,1e-08,1e-08,1e-08,1e-08,1e-07,1e-08,1e-05]
+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/test417.m
===================================================================
--- /issm/trunk/test/NightlyRun/test417.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test417.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -50,5 +50,5 @@
 md.diagnostic.reltol=10^-5; %tighten for qmu analyses
 
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test418.m
===================================================================
--- /issm/trunk/test/NightlyRun/test418.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test418.m	(revision 13975)
@@ -1,4 +1,4 @@
 %test partitioning, and partition averaging
-md=triangle(model,'../Exp/Square.exp',30000);
+md=triangle(model(),'../Exp/Square.exp',30000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
Index: /issm/trunk/test/NightlyRun/test419.m
===================================================================
--- /issm/trunk/test/NightlyRun/test419.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test419.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=extrude(md,5,1.);
 md=setflowequation(md,'macayeal','../Exp/SquareHalfRight.exp','fill','pattyn');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test419.py
===================================================================
--- /issm/trunk/test/NightlyRun/test419.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test419.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test420.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',200000);
+md=triangle(model(),'../Exp/Square.exp',200000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -32,5 +32,5 @@
 
 %solve
-md=solve(md,DiagnosticSolutionEnum,'overwrite','y');
+md=solve(md,DiagnosticSolutionEnum(),'overwrite','y');
 md.qmu.results=md.results.dakota;
 
Index: /issm/trunk/test/NightlyRun/test421.m
===================================================================
--- /issm/trunk/test/NightlyRun/test421.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test421.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=extrude(md,5,1.);
 md=setflowequation(md,'stokes','../Exp/SquareHalfRight.exp','fill','pattyn');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test421.py
===================================================================
--- /issm/trunk/test/NightlyRun/test421.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test421.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test422.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test422.py
===================================================================
--- /issm/trunk/test/NightlyRun/test422.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test422.py	(revision 13975)
@@ -0,0 +1,29 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'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: /issm/trunk/test/NightlyRun/test423.m
===================================================================
--- /issm/trunk/test/NightlyRun/test423.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test423.m	(revision 13975)
@@ -1,12 +1,12 @@
-radius=1e6;
-shelfextent=2e5;
+radius=1.e6;
+shelfextent=2.e5;
 
-md=roundmesh(model,radius,50000);
+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;
+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);
@@ -25,9 +25,9 @@
 %test different grounding line dynamics.
 md.groundingline.migration='AgressiveMigration';
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 element_on_iceshelf_agressive=(md.results.TransientSolution.MaskElementonfloatingice);
 
 md.groundingline.migration='SoftMigration';
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 element_on_iceshelf_soft=(md.results.TransientSolution.MaskElementonfloatingice);
 
Index: /issm/trunk/test/NightlyRun/test423.py
===================================================================
--- /issm/trunk/test/NightlyRun/test423.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test423.py	(revision 13975)
@@ -0,0 +1,48 @@
+import numpy
+from model import *
+from roundmesh import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+radius=1.e6
+shelfextent=2.e5
+
+md=roundmesh(model(),radius,50000.)
+#fix center node to 0,0
+rad=numpy.sqrt(md.mesh.x**2+md.mesh.y**2)
+pos=numpy.argmin(rad)
+md.mesh.x[pos]=0.
+md.mesh.y[pos]=0.    #the closest node to the center is changed to be exactly at the center
+xelem=numpy.mean(md.mesh.x[md.mesh.elements.astype(int)-1],axis=1)
+yelem=numpy.mean(md.mesh.y[md.mesh.elements.astype(int)-1],axis=1)
+rad=numpy.sqrt(xelem**2+yelem**2)
+flags=numpy.zeros(md.mesh.numberofelements)
+pos=numpy.nonzero(rad>=(radius-shelfextent))
+flags[pos]=1
+md=setmask(md,flags,'') 
+md=parameterize(md,'../Par/RoundSheetShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.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[0].MaskElementonfloatingice
+
+md.groundingline.migration='SoftMigration'
+md=solve(md,TransientSolutionEnum())
+element_on_iceshelf_soft=md.results.TransientSolution[0].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 13974)
+++ /issm/trunk/test/NightlyRun/test424.m	(revision 13975)
@@ -1,14 +1,13 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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.initialization.vx(:)=0.;
+md.initialization.vy(:)=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.surfaceforcings.mass_balance(:)=100.;
 md.transient.isdiagnostic=0;
 md.transient.isgroundingline=1;
@@ -16,5 +15,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test424.py
===================================================================
--- /issm/trunk/test/NightlyRun/test424.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test424.py	(revision 13975)
@@ -0,0 +1,49 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.bed=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bathymetry=-700.-abs(md.mesh.y.reshape(-1,1)-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[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test425.m
===================================================================
--- /issm/trunk/test/NightlyRun/test425.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test425.m	(revision 13975)
@@ -1,14 +1,13 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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.initialization.vx(:)=0.;
+md.initialization.vy(:)=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.surfaceforcings.mass_balance(:)=-150.;
 md.transient.isdiagnostic=0;
 md.transient.isgroundingline=1;
@@ -16,5 +15,5 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test425.py
===================================================================
--- /issm/trunk/test/NightlyRun/test425.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test425.py	(revision 13975)
@@ -0,0 +1,49 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=setflowequation(md,'macayeal','all')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.bed=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bathymetry=-700.-abs(md.mesh.y.reshape(-1,1)-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[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test426.m
===================================================================
--- /issm/trunk/test/NightlyRun/test426.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test426.m	(revision 13975)
@@ -1,16 +1,14 @@
-md=triangle(model,'../Exp/Square.exp',350000);
+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.initialization.vx(:)=0.;
+md.initialization.vy(:)=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.surfaceforcings.mass_balance(:)=100.;
+md=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
-
 md.transient.isdiagnostic=0;
 md.transient.isgroundingline=1;
@@ -18,5 +16,5 @@
 md.cluster=generic('name',oshostname(),'np',3);
 
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
@@ -25,5 +23,5 @@
 	'Bed3','Surface3','Thickness3','Floatingice3'};
 field_tolerances={1e-13,1e-13,1e-13,1e-13,...
-	1e-11,1e-11,1e-11,1e-13,...
+	1e-11,1e-10,1e-11,1e-13,...
 	1e-10,1e-10,1e-10,1e-13};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test426.py
===================================================================
--- /issm/trunk/test/NightlyRun/test426.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test426.py	(revision 13975)
@@ -0,0 +1,50 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',350000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.bed=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bathymetry=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1000.
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md.surfaceforcings.mass_balance[:]=100.
+md.extrude(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-10,1e-11,1e-13,\
+	1e-10,1e-10,1e-10,1e-13]
+field_values=[\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	md.results.TransientSolution[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,\
+	]
Index: /issm/trunk/test/NightlyRun/test427.m
===================================================================
--- /issm/trunk/test/NightlyRun/test427.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test427.m	(revision 13975)
@@ -1,14 +1,13 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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.initialization.vx(:)=0.;
+md.initialization.vy(:)=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=extrude(md,3,1.);
 
 md.surfaceforcings.mass_balance(:)=-150;
@@ -17,5 +16,5 @@
 md.groundingline.migration='SoftMigration';
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test427.py
===================================================================
--- /issm/trunk/test/NightlyRun/test427.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test427.py	(revision 13975)
@@ -0,0 +1,50 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.initialization.vx[:]=0.
+md.initialization.vy[:]=0.
+md.geometry.bed=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.bathymetry=-700.-abs(md.mesh.y.reshape(-1,1)-500000.)/1000.
+md.geometry.thickness[:]=1300
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+md=setflowequation(md,'macayeal','all')
+md.extrude(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[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].MaskElementonfloatingice,\
+	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,\
+	]
Index: /issm/trunk/test/NightlyRun/test428.m
===================================================================
--- /issm/trunk/test/NightlyRun/test428.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test428.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+md=triangle(model(),'../Exp/Square.exp',150000.);
 md=setmask(md,'../Exp/SquareShelf.exp','');
 md=parameterize(md,'../Par/SquareSheetShelf.par');
@@ -6,5 +6,5 @@
 md.diagnostic.restol=0.0001;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test428.py
===================================================================
--- /issm/trunk/test/NightlyRun/test428.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test428.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md=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: /issm/trunk/test/NightlyRun/test429.m
===================================================================
--- /issm/trunk/test/NightlyRun/test429.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test429.m	(revision 13975)
@@ -1,11 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test429.py
===================================================================
--- /issm/trunk/test/NightlyRun/test429.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test429.py	(revision 13975)
@@ -0,0 +1,30 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(5,1.)
+md=setflowequation(md,'pattyn','all')
+md.diagnostic.isnewton=1
+md.diagnostic.restol=0.0001
+md.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 13974)
+++ /issm/trunk/test/NightlyRun/test430.m	(revision 13975)
@@ -1,11 +1,11 @@
-md=triangle(model,'../Exp/Square.exp',180000);
+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=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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test430.py
===================================================================
--- /issm/trunk/test/NightlyRun/test430.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test430.py	(revision 13975)
@@ -0,0 +1,30 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',180000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(3,1.)
+md=setflowequation(md,'stokes','all')
+md.diagnostic.isnewton=1
+md.diagnostic.restol=0.0001
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,DiagnosticSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Vx','Vy','Vz','Vel','Pressure']
+field_tolerances=[1e-07,1e-07,1e-06,1e-07,1e-07]
+field_values=[\
+	md.results.DiagnosticSolution.Vx,\
+	md.results.DiagnosticSolution.Vy,\
+	md.results.DiagnosticSolution.Vz,\
+	md.results.DiagnosticSolution.Vel,\
+	md.results.DiagnosticSolution.Pressure,\
+	]
Index: /issm/trunk/test/NightlyRun/test431.m
===================================================================
--- /issm/trunk/test/NightlyRun/test431.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test431.m	(revision 13975)
@@ -1,12 +1,12 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,3,2.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
+md.timestepping.time_step=0.;
 md.thermal.isenthalpy=1;
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,SteadystateSolutionEnum);
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test431.py
===================================================================
--- /issm/trunk/test/NightlyRun/test431.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test431.py	(revision 13975)
@@ -0,0 +1,34 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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=numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test432.m	(revision 13975)
@@ -1,12 +1,12 @@
-md=triangle(model,'../Exp/Square.exp',150000);
+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=extrude(md,3,2.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
+md.timestepping.time_step=0.;
 md.thermal.isenthalpy=1;
 md.initialization.waterfraction=zeros(md.mesh.numberofvertices,1);
-md=solve(md,SteadystateSolutionEnum);
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test432.py
===================================================================
--- /issm/trunk/test/NightlyRun/test432.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test432.py	(revision 13975)
@@ -0,0 +1,34 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Square.exp',150000.)
+md=setmask(md,'../Exp/SquareShelf.exp','')
+md=parameterize(md,'../Par/SquareSheetShelf.py')
+md.extrude(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=numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test501.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test501.py
===================================================================
--- /issm/trunk/test/NightlyRun/test501.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test501.py	(revision 13975)
@@ -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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+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 13974)
+++ /issm/trunk/test/NightlyRun/test502.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -5,5 +5,5 @@
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test502.py
===================================================================
--- /issm/trunk/test/NightlyRun/test502.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test502.py	(revision 13975)
@@ -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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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','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 13974)
+++ /issm/trunk/test/NightlyRun/test503.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+md=triangle(model(),'../Exp/Pig.exp',20000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -5,5 +5,5 @@
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test503.py
===================================================================
--- /issm/trunk/test/NightlyRun/test503.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test503.py	(revision 13975)
@@ -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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test504.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+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,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test504.py
===================================================================
--- /issm/trunk/test/NightlyRun/test504.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test504.py	(revision 13975)
@@ -0,0 +1,35 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md=setflowequation(md,'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']
+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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test505.m
===================================================================
--- /issm/trunk/test/NightlyRun/test505.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test505.m	(revision 13975)
@@ -1,14 +1,15 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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_tolerances={1e-12,1e-12,1e-10,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,...
+						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,1e-12,1e-11,1e-8};
 field_values={...
 	(md.results.TransientSolution(1).Vx),...
Index: /issm/trunk/test/NightlyRun/test505.py
===================================================================
--- /issm/trunk/test/NightlyRun/test505.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test505.py	(revision 13975)
@@ -0,0 +1,44 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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-10,1e-12,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13, \
+						1e-13,1e-12,1e-10,1e-12,1e-13,1e-11,1e-11,1e-12,1e-11,1e-8]
+field_values=[\
+	md.results.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test506.m
===================================================================
--- /issm/trunk/test/NightlyRun/test506.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test506.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,2,1.);
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test506.py
===================================================================
--- /issm/trunk/test/NightlyRun/test506.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test506.py	(revision 13975)
@@ -0,0 +1,44 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(2,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']
+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.TransientSolution[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test507.m
===================================================================
--- /issm/trunk/test/NightlyRun/test507.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test507.m	(revision 13975)
@@ -1,12 +1,11 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,2,1.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,TransientSolutionEnum);
+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'};
Index: /issm/trunk/test/NightlyRun/test507.py
===================================================================
--- /issm/trunk/test/NightlyRun/test507.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test507.py	(revision 13975)
@@ -0,0 +1,43 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(2,1.)
+md=setflowequation(md,'stokes','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-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[0].Vx,\
+	md.results.TransientSolution[0].Vy,\
+	md.results.TransientSolution[0].Vz,\
+	md.results.TransientSolution[0].Vel,\
+	md.results.TransientSolution[0].Pressure,\
+	md.results.TransientSolution[0].Bed,\
+	md.results.TransientSolution[0].Surface,\
+	md.results.TransientSolution[0].Thickness,\
+	md.results.TransientSolution[0].Temperature,\
+	md.results.TransientSolution[0].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,\
+	]
Index: /issm/trunk/test/NightlyRun/test508.m
===================================================================
--- /issm/trunk/test/NightlyRun/test508.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test508.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+md=triangle(model(),'../Exp/Pig.exp',30000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -5,11 +5,10 @@
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
+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-08
-};
+field_tolerances={1e-09,1e-09,1e-09,1e-09,1e-09,1e-09,1e-08};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test508.py
===================================================================
--- /issm/trunk/test/NightlyRun/test508.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test508.py	(revision 13975)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(4,1.1)
+md=setflowequation(md,'macayeal','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-08]
+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/test509.m
===================================================================
--- /issm/trunk/test/NightlyRun/test509.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test509.m	(revision 13975)
@@ -1,10 +1,10 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=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);
+md.timestepping.time_step=0.;
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test509.py
===================================================================
--- /issm/trunk/test/NightlyRun/test509.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test509.py	(revision 13975)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test510.m	(revision 13975)
@@ -1,15 +1,14 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+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,2,1.);
 md=setflowequation(md,'stokes','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md.timestepping.time_step=0;
-md=solve(md,SteadystateSolutionEnum);
+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_tolerances={1e-08,1e-08,1e-08,1e-08,1e-08,1e-08,1e-06};
 field_values={...
 	(md.results.SteadystateSolution.Vx),...
Index: /issm/trunk/test/NightlyRun/test510.py
===================================================================
--- /issm/trunk/test/NightlyRun/test510.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test510.py	(revision 13975)
@@ -0,0 +1,30 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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: /issm/trunk/test/NightlyRun/test511.m
===================================================================
--- /issm/trunk/test/NightlyRun/test511.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test511.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/Pig.exp',10000);
+md=triangle(model(),'../Exp/Pig.exp',10000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -6,5 +6,5 @@
 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=extrude(md,3,1.);
 md=setflowequation(md,'stokes','all');
 md=extract(md,md.mask.elementonfloatingice);
@@ -13,23 +13,23 @@
 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.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.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);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'MaterialsRheologyB' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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.J),...
 	(md.results.DiagnosticSolution.MaterialsRheologyB),...
 	(md.results.DiagnosticSolution.Pressure),...
Index: /issm/trunk/test/NightlyRun/test511.py
===================================================================
--- /issm/trunk/test/NightlyRun/test511.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test511.py	(revision 13975)
@@ -0,0 +1,50 @@
+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/Pig.exp',10000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+
+#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(3,1.)
+md=setflowequation(md,'stokes','all')
+md=md.extract(md.mask.elementonfloatingice)
+
+#control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['MaterialsRheologyBbar']
+md.inversion.min_parameters=10.**6*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=2.*10**9*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=101*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.gradient_scaling=10.**8*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test512.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Pig.exp',20000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 
@@ -8,10 +8,10 @@
 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.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.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);
@@ -19,8 +19,8 @@
 
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,DiagnosticSolutionEnum);
+md=solve(md,DiagnosticSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy'};
+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={...
Index: /issm/trunk/test/NightlyRun/test512.py
===================================================================
--- /issm/trunk/test/NightlyRun/test512.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test512.py	(revision 13975)
@@ -0,0 +1,46 @@
+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/Pig.exp',20000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(3,1.)
+md=setflowequation(md,'pattyn','all')
+
+# control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=2.99*numpy.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: /issm/trunk/test/NightlyRun/test513.m
===================================================================
--- /issm/trunk/test/NightlyRun/test513.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test513.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 
@@ -8,21 +8,21 @@
 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.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.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.timestepping.time_step=0.;
 
 md.thermal.penalty_lock=5;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SteadystateSolutionEnum);
+md=solve(md,SteadystateSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'FrictionCoefficient' 'Pressure' 'Vel' 'Vx' 'Vy' 'Vz' 'Temperature' 'BasalforcingsMeltingRate'};
+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={...
Index: /issm/trunk/test/NightlyRun/test513.py
===================================================================
--- /issm/trunk/test/NightlyRun/test513.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test513.py	(revision 13975)
@@ -0,0 +1,50 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(3,1.)
+md=setflowequation(md,'macayeal','all')
+
+# control parameters
+md.inversion.iscontrol=1
+md.inversion.control_parameters=['FrictionCoefficient']
+md.inversion.min_parameters=1.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=200.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.nsteps=2
+md.inversion.cost_functions=numpy.hstack((103*numpy.ones((md.inversion.nsteps,1)),501*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,2))
+md.inversion.cost_functions_coefficients[:,1]=2.*10**-7
+md.inversion.gradient_scaling=3.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=2.*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test514.m	(revision 13975)
@@ -1,11 +1,11 @@
 %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);
+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=bamg(model(),'domain','../Exp/Pig.exp','hmax',10000.);
 md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp');
 md=parameterize(md,'../Par/Pig.par');
@@ -15,12 +15,12 @@
 %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,[]);
+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);
+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);
+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;
@@ -29,21 +29,21 @@
 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);
+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);
+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]); 
+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_names     ={'x1y1x2y2x3y3x4y4x5y5x6y6'  'x7y7' };
+field_tolerances={1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13,1e-13};
 field_values={...
 	x1, y1,...
Index: /issm/trunk/test/NightlyRun/test514.py
===================================================================
--- /issm/trunk/test/NightlyRun/test514.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test514.py	(revision 13975)
@@ -0,0 +1,66 @@
+import numpy
+import copy
+from model import *
+from bamg import *
+from setmask import *
+from parameterize import *
+from ComputeHessian import *
+from ComputeMetric import *
+from MatlabFuncs import *
+
+#Simple mesh 1
+hVertices=10000.*numpy.ones((27,1))
+hVertices[0: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.py')
+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(copy.deepcopy(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(copy.deepcopy(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=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+hVertices[numpy.nonzero(md.mesh.vertexonboundary)]=500.
+md2=bamg(copy.deepcopy(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(copy.deepcopy(md),'field',md.inversion.vy_obs,'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',0,'err',numpy.array([[1.]]))
+x6=md2.mesh.x
+y6=md2.mesh.y
+
+#refine existing mesh 5
+md2=bamg(copy.deepcopy(md),'field',numpy.hstack((md.inversion.vy_obs,md.geometry.thickness)),'hmin',1000.,'hmax',20000.,'gradation',3.,'geometricalmetric',1,'Hessiantype',1,'err',numpy.array([[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: /issm/trunk/test/NightlyRun/test515.m
===================================================================
--- /issm/trunk/test/NightlyRun/test515.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test515.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.thermal.stabilization=2;
@@ -10,5 +10,5 @@
 md.transient.isthermal=1;
 md.transient.isgroundingline=0;
-md=solve(md,TransientSolutionEnum);
+md=solve(md,TransientSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test515.py
===================================================================
--- /issm/trunk/test/NightlyRun/test515.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test515.py	(revision 13975)
@@ -0,0 +1,32 @@
+from model import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from EnumDefinitions import *
+from solve import *
+from MatlabFuncs import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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[0].Temperature,\
+	md.results.TransientSolution[0].BasalforcingsMeltingRate,\
+	md.results.TransientSolution[1].Temperature,\
+	md.results.TransientSolution[1].BasalforcingsMeltingRate,\
+	]
Index: /issm/trunk/test/NightlyRun/test516.m
===================================================================
--- /issm/trunk/test/NightlyRun/test516.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test516.m	(revision 13975)
@@ -1,6 +1,6 @@
-md=triangle(model,'../Exp/Pig.exp',30000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'pattyn','all');
 md.thermal.stabilization=2;
@@ -8,5 +8,5 @@
 md.timestepping.time_step=0;
 md.thermal.penalty_threshold=40;
-md=solve(md,ThermalSolutionEnum);
+md=solve(md,ThermalSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test516.py
===================================================================
--- /issm/trunk/test/NightlyRun/test516.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test516.py	(revision 13975)
@@ -0,0 +1,28 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/Pig.exp',30000.)
+md=setmask(md,'../Exp/PigShelves.exp','../Exp/PigIslands.exp')
+md=parameterize(md,'../Par/Pig.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test601.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test601.py
===================================================================
--- /issm/trunk/test/NightlyRun/test601.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test601.py	(revision 13975)
@@ -0,0 +1,22 @@
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=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 13974)
+++ /issm/trunk/test/NightlyRun/test602.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
@@ -7,5 +7,5 @@
 md.prognostic.spcthickness=md.geometry.thickness;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test602.py
===================================================================
--- /issm/trunk/test/NightlyRun/test602.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test602.py	(revision 13975)
@@ -0,0 +1,27 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=meshconvert(md)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=setflowequation(md,'macayeal','all')
+md.prognostic.stabilization=3
+md.prognostic.spcthickness=md.geometry.thickness
+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/test603.m
===================================================================
--- /issm/trunk/test/NightlyRun/test603.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test603.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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=extrude(md,6,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,PrognosticSolutionEnum);
+md=solve(md,PrognosticSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test603.py
===================================================================
--- /issm/trunk/test/NightlyRun/test603.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test603.py	(revision 13975)
@@ -0,0 +1,24 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test604.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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,SurfaceSlopeSolutionEnum);
+md=solve(md,SurfaceSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test604.py
===================================================================
--- /issm/trunk/test/NightlyRun/test604.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test604.py	(revision 13975)
@@ -0,0 +1,24 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=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/test605.m
===================================================================
--- /issm/trunk/test/NightlyRun/test605.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test605.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
@@ -5,5 +5,5 @@
 md=setflowequation(md,'pattyn','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,SurfaceSlopeSolutionEnum);
+md=solve(md,SurfaceSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test605.py
===================================================================
--- /issm/trunk/test/NightlyRun/test605.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test605.py	(revision 13975)
@@ -0,0 +1,25 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test606.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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,BedSlopeSolutionEnum);
+md=solve(md,BedSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test606.py
===================================================================
--- /issm/trunk/test/NightlyRun/test606.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test606.py	(revision 13975)
@@ -0,0 +1,24 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=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/test607.m
===================================================================
--- /issm/trunk/test/NightlyRun/test607.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test607.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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=extrude(md,2,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BedSlopeSolutionEnum);
+md=solve(md,BedSlopeSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test607.py
===================================================================
--- /issm/trunk/test/NightlyRun/test607.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test607.py	(revision 13975)
@@ -0,0 +1,25 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md.extrude(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 13974)
+++ /issm/trunk/test/NightlyRun/test608.m	(revision 13975)
@@ -1,8 +1,8 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test608.py
===================================================================
--- /issm/trunk/test/NightlyRun/test608.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test608.py	(revision 13975)
@@ -0,0 +1,23 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=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/test609.m
===================================================================
--- /issm/trunk/test/NightlyRun/test609.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test609.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
@@ -6,5 +6,5 @@
 md.balancethickness.stabilization=3;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test609.py
===================================================================
--- /issm/trunk/test/NightlyRun/test609.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test609.py	(revision 13975)
@@ -0,0 +1,26 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=meshconvert(md)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=setflowequation(md,'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 13974)
+++ /issm/trunk/test/NightlyRun/test610.m	(revision 13975)
@@ -1,9 +1,9 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+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=extrude(md,3,1.);
 md=setflowequation(md,'macayeal','all');
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
Index: /issm/trunk/test/NightlyRun/test610.py
===================================================================
--- /issm/trunk/test/NightlyRun/test610.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test610.py	(revision 13975)
@@ -0,0 +1,24 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md.extrude(3,1.)
+md=setflowequation(md,'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/test611.m
===================================================================
--- /issm/trunk/test/NightlyRun/test611.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test611.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
 md=parameterize(md,'../Par/79North.par');
@@ -10,17 +10,17 @@
 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.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.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);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_names     ={'Gradient','Misfits','BalancethicknessThickeningRate','Thickness'};
 field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test611.py
===================================================================
--- /issm/trunk/test/NightlyRun/test611.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test611.py	(revision 13975)
@@ -0,0 +1,41 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=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.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=50.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.gradient_scaling=10./md.constants.yts*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=4*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.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 13974)
+++ /issm/trunk/test/NightlyRun/test612.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
@@ -11,17 +11,17 @@
 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.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.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);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient' 'Misfits' 'BalancethicknessThickeningRate' 'Thickness'};
+field_names     ={'Gradient','Misfits','BalancethicknessThickeningRate','Thickness'};
 field_tolerances={1e-12,1e-12,1e-12,1e-12,1e-12,1e-12};
 field_values={...
Index: /issm/trunk/test/NightlyRun/test612.py
===================================================================
--- /issm/trunk/test/NightlyRun/test612.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test612.py	(revision 13975)
@@ -0,0 +1,43 @@
+import numpy
+from model import *
+from EnumDefinitions import *
+from MatlabFuncs import *
+from triangle import *
+from meshconvert import *
+from setmask import *
+from parameterize import *
+from setflowequation import *
+from solve import *
+
+md=triangle(model(),'../Exp/79North.exp',10000.)
+md=meshconvert(md)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=setflowequation(md,'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.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.max_parameters=50.*numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.gradient_scaling=10./md.constants.yts*numpy.ones((md.inversion.nsteps,1))
+md.inversion.maxiter_per_step=4*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.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/test613.m
===================================================================
--- /issm/trunk/test/NightlyRun/test613.m	(revision 13974)
+++ /issm/trunk/test/NightlyRun/test613.m	(revision 13975)
@@ -1,3 +1,3 @@
-md=triangle(model,'../Exp/79North.exp',10000);
+md=triangle(model(),'../Exp/79North.exp',10000.);
 md=meshconvert(md);
 md=setmask(md,'../Exp/79NorthShelf.exp','');
@@ -13,11 +13,10 @@
 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.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.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);
@@ -27,13 +26,13 @@
 md.verbose.control=1;
 md.cluster=generic('name',oshostname(),'np',3);
-md=solve(md,BalancethicknessSolutionEnum);
+md=solve(md,BalancethicknessSolutionEnum());
 
 %Fields and tolerances to track changes
-field_names     ={'Gradient1' 'Gradient2' 'Misfits' 'Vx' 'Vy' 'Thickness'};
+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.J),...
 	(md.results.BalancethicknessSolution.Vx),...
 	(md.results.BalancethicknessSolution.Vy),...
Index: /issm/trunk/test/NightlyRun/test613.py
===================================================================
--- /issm/trunk/test/NightlyRun/test613.py	(revision 13975)
+++ /issm/trunk/test/NightlyRun/test613.py	(revision 13975)
@@ -0,0 +1,52 @@
+import numpy
+import copy
+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/79North.exp',10000.)
+md=meshconvert(md)
+md=setmask(md,'../Exp/79NorthShelf.exp','')
+md=parameterize(md,'../Par/79North.py')
+md=setflowequation(md,'macayeal','all')
+
+#Ice sheet only
+md=md.extract(md.mask.elementongroundedice)
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+
+#control parameters
+md.inversion.thickness_obs=copy.deepcopy(md.geometry.thickness)
+md.inversion.iscontrol=1
+md.inversion.nsteps=2
+md.inversion.control_parameters=['Vx','Vy']
+md.balancethickness.stabilization=1
+md.inversion.gradient_scaling=numpy.hstack((10./md.constants.yts*numpy.ones((md.inversion.nsteps,1)),10./md.constants.yts*numpy.ones((md.inversion.nsteps,1))))
+md.inversion.min_parameters=numpy.hstack((-2000.*numpy.ones((md.mesh.numberofvertices,1)),-2000.*numpy.ones((md.mesh.numberofvertices,1))))
+md.inversion.max_parameters=numpy.hstack((+2000.*numpy.ones((md.mesh.numberofvertices,1)),+2000.*numpy.ones((md.mesh.numberofvertices,1))))
+md.inversion.cost_functions=201*numpy.ones((md.inversion.nsteps,1))
+md.inversion.cost_functions_coefficients=numpy.ones((md.mesh.numberofvertices,1))
+md.inversion.maxiter_per_step=4*numpy.ones((md.inversion.nsteps,1))
+md.inversion.step_threshold=0.99*numpy.ones((md.inversion.nsteps,1))
+
+md.verbose.control=1
+md.cluster=generic('name',oshostname(),'np',3)
+md=solve(md,BalancethicknessSolutionEnum())
+
+#Fields and tolerances to track changes
+field_names     =['Gradient1','Gradient2','Misfits','Vx','Vy','Thickness']
+field_tolerances=[1e-12,1e-12,1e-12,1e-12,1e-12,1e-12]
+field_values=[\
+	md.results.BalancethicknessSolution.Gradient1,\
+	md.results.BalancethicknessSolution.Gradient2,\
+	md.results.BalancethicknessSolution.J,\
+	md.results.BalancethicknessSolution.Vx,\
+	md.results.BalancethicknessSolution.Vy,\
+	md.results.BalancethicknessSolution.Thickness,\
+]
Index: /issm/trunk/test/Par/79North.par
===================================================================
--- /issm/trunk/test/Par/79North.par	(revision 13974)
+++ /issm/trunk/test/Par/79North.par	(revision 13975)
@@ -9,6 +9,6 @@
 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);
+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.geometry.surface  =InterpFromMeshToMesh2d(index,x,y,surface,md.mesh.x,md.mesh.y);
 md.geometry.thickness=InterpFromMeshToMesh2d(index,x,y,thickness,md.mesh.x,md.mesh.y);
@@ -23,15 +23,14 @@
 %Friction
 pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient=50*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient=50.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
 
 %Ice shelf melting and surface mass balance 
+pos=find(md.mask.elementonfloatingice);
 md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-pos=zeros(md.mesh.numberofvertices,1);
-pos(md.mesh.elements(find(md.mask.elementonfloatingice),:))=1;
-md.basalforcings.melting_rate(find(pos))=10;
-md.surfaceforcings.mass_balance=15*ones(md.mesh.numberofvertices,1);
+md.basalforcings.melting_rate(md.mesh.elements(pos,:))=10;
+md.surfaceforcings.mass_balance=15.*ones(md.mesh.numberofvertices,1);
 
 %Numerical parameters
@@ -41,6 +40,6 @@
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
-md.timestepping.time_step=1;
-md.timestepping.final_time=3;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
 md.diagnostic.restol=0.05;
 md.diagnostic.reltol=0.005;
Index: /issm/trunk/test/Par/79North.py
===================================================================
--- /issm/trunk/test/Par/79North.py	(revision 13975)
+++ /issm/trunk/test/Par/79North.py	(revision 13975)
@@ -0,0 +1,69 @@
+import os.path
+import inspect
+import netCDF4
+from numpy import *
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetMarineIceSheetBC import *
+
+#Start defining model parameters here
+
+#Geometry and observation
+f         = netCDF4.Dataset('../Data/79North.nc','r')
+x         = reshape(f.variables['x'][:],(-1))
+y         = reshape(f.variables['y'][:],(-1))
+vx        = f.variables['vx'][:]
+vy        = f.variables['vy'][:]
+index     = f.variables['index'][:]
+surface   = f.variables['surface'][:]
+thickness = f.variables['thickness'][:]
+f.close()
+
+[md.initialization.vx]  = InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]  = InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+[md.geometry.surface]   = InterpFromMeshToMesh2d(index,x,y,surface,md.mesh.x,md.mesh.y)
+[md.geometry.thickness] = InterpFromMeshToMesh2d(index,x,y,thickness,md.mesh.x,md.mesh.y)
+md.geometry.bed         = md.geometry.surface-md.geometry.thickness
+
+#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))
+md.initialization.temperature=md.initialization.temperature
+
+#Friction
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.p=ones((md.mesh.numberofelements,1))
+md.friction.q=ones((md.mesh.numberofelements,1))
+
+#Ice shelf melting and surface mass balance 
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.basalforcings.melting_rate=zeros((md.mesh.numberofvertices,1))
+md.basalforcings.melting_rate[md.mesh.elements[pos].astype(int)-1]=10.
+md.surfaceforcings.mass_balance=15*numpy.ones((md.mesh.numberofvertices,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot=0.3
+md.prognostic.stabilization=1
+md.thermal.stabilization=1
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+md.diagnostic.restol=0.05
+md.diagnostic.reltol=0.005
+md.steadystate.reltol=0.005
+md.diagnostic.abstol=float('NaN')
+
+#Boundary conditions:
+md=SetMarineIceSheetBC(md)
+pos=numpy.nonzero(md.mesh.vertexonboundary)
+md.balancethickness.spcthickness[pos]=md.geometry.thickness[pos]
+md.prognostic.spcthickness[pos]=md.geometry.thickness[pos]
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/Pig.py
===================================================================
--- /issm/trunk/test/Par/Pig.py	(revision 13975)
+++ /issm/trunk/test/Par/Pig.py	(revision 13975)
@@ -0,0 +1,63 @@
+import os.path
+import inspect
+import netCDF4
+from numpy import *
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetMarineIceSheetBC import *
+
+#Start defining model parameters here
+
+#Geometry and observation
+f = netCDF4.Dataset('../Data/Pig.nc','r')
+x         = reshape(f.variables['x'][:],(-1))
+y         = reshape(f.variables['y'][:],(-1))
+vx_obs    = f.variables['vx_obs'][:]
+vy_obs    = f.variables['vy_obs'][:]
+index     = f.variables['index'][:]
+surface   = f.variables['surface'][:]
+thickness = f.variables['thickness'][:]
+f.close()
+
+[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)
+[md.geometry.surface]  =InterpFromMeshToMesh2d(index,x,y,surface,md.mesh.x,md.mesh.y)
+[md.geometry.thickness]=InterpFromMeshToMesh2d(index,x,y,thickness,md.mesh.x,md.mesh.y)
+md.geometry.bed=md.geometry.surface-md.geometry.thickness
+md.initialization.vx=md.inversion.vx_obs
+md.initialization.vy=md.inversion.vy_obs
+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))
+md.initialization.temperature=md.initialization.temperature
+
+#Friction
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=50.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.p=ones((md.mesh.numberofelements,1))
+md.friction.q=ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot=0.3
+md.prognostic.stabilization=1.
+md.verbose=verbose(0)
+md.settings.waitonlock=30.
+md.timestepping.time_step=1.
+md.timestepping.final_time=2.
+md.diagnostic.restol=0.05
+md.diagnostic.reltol=1.
+md.steadystate.reltol=1.
+md.diagnostic.abstol=float('nan')
+
+#Boundary conditions:
+md=SetMarineIceSheetBC(md)
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/RoundSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.par	(revision 13974)
+++ /issm/trunk/test/Par/RoundSheetShelf.par	(revision 13975)
@@ -2,9 +2,9 @@
 
 di=md.materials.rho_ice/md.materials.rho_water;
-rad=1e6;
-shelfextent=2e5;
+rad=1.e6;
+shelfextent=2.e5;
 %Geometry
-hmin=300;
-hmax=1000;
+hmin=300.;
+hmax=1000.;
 radius=sqrt((md.mesh.x).*md.mesh.x+(md.mesh.y).*md.mesh.y);
 ymin=min(radius);
@@ -14,21 +14,20 @@
 
 pos=find(md.mask.vertexongroundedice);
-md.geometry.bed(pos)=md.geometry.bed(pos)-300*(radius(pos)-(rad-shelfextent))/(rad-shelfextent);
+md.geometry.bed(pos)=md.geometry.bed(pos)-300.*(radius(pos)-(rad-shelfextent))/(rad-shelfextent);
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
 
 pos=find(radius<200000);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
 
-
-pos=find(md.mesh.x<.2*1e6 & md.mesh.x>-.2*1e6 & md.mesh.y>0);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+pos=find(md.mesh.x<0.2*1.e6 & md.mesh.x>-0.2*1.e6 & md.mesh.y>0.);
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
 
-pos=find(md.mesh.x<.1*1e6 & md.mesh.x>-.1*1e6 & md.mesh.y<-.5*1e6 & md.mesh.y>-.6*1e6);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+pos=find(md.mesh.x<0.1*1.e6 & md.mesh.x>-0.1*1.e6 & md.mesh.y<-0.5*1.e6 & md.mesh.y>-0.6*1.e6);
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
 
@@ -36,18 +35,19 @@
 di=md.materials.rho_ice/md.materials.rho_water;
 rad=sqrt(md.mesh.x.^2+md.mesh.y.^2);
-pos=find(rad<200000);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+pos=find(rad<200000.);
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
 
-pos=find(md.mesh.x<.2*1e6 & md.mesh.x>-.2*1e6 & md.mesh.y>0);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+pos=find(md.mesh.x<0.2*1.e6 & md.mesh.x>-0.2*1.e6 & md.mesh.y>0.);
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
 
-pos=find(md.mesh.x<.1*1e6 & md.mesh.x>-.1*1e6 & md.mesh.y<-.5*1e6 & md.mesh.y>-.6*1e6);
-md.geometry.thickness(pos)=100;
-md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20;
+pos=find(md.mesh.x<0.1*1.e6 & md.mesh.x>-0.1*1.e6 & md.mesh.y<-0.5*1.e6 & md.mesh.y>-0.6*1.e6);
+md.geometry.thickness(pos)=100.;
+md.geometry.bed(pos)=-di*md.geometry.thickness(pos)-20.;
 md.geometry.surface(pos)=md.geometry.bed(pos)+md.geometry.thickness(pos);
+
 %Initial velocity 
 md.initialization.vx=zeros(md.mesh.numberofvertices,1);
@@ -57,17 +57,17 @@
 
 %Materials
-md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+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);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
 %Surface mass balance and basal melting
-md.surfaceforcings.mass_balance=-10*ones(md.mesh.numberofvertices,1);
+md.surfaceforcings.mass_balance=-10.*ones(md.mesh.numberofvertices,1);
 md.basalforcings.melting_rate=zeros(md.mesh.numberofvertices,1);
-pos=find(md.mask.vertexonfloatingice);md.basalforcings.melting_rate(pos)=10;
+pos=find(md.mask.vertexonfloatingice);md.basalforcings.melting_rate(pos)=10.;
 md.basalforcings.geothermalflux=ones(md.mesh.numberofvertices,1);
 
 %Friction
 pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
 md.friction.coefficient(md.mesh.elements(pos,:))=0;
 md.friction.p=ones(md.mesh.numberofelements,1);
@@ -84,11 +84,11 @@
 md.steadystate.reltol=0.05;
 md.diagnostic.abstol=NaN;
-md.timestepping.time_step=5;
-md.timestepping.final_time=5;
+md.timestepping.time_step=5.;
+md.timestepping.final_time=5.;
 
 %bathymetry and grounding line migration:
 md.groundingline.migration='AgressiveMigration';
 md.geometry.bathymetry=md.geometry.bed;
-pos=find(md.mask.vertexonfloatingice); md.geometry.bathymetry(pos)=md.geometry.bed(pos)-900;
+pos=find(md.mask.vertexonfloatingice); md.geometry.bathymetry(pos)=md.geometry.bed(pos)-900.;
 
 %Deal with boundary conditions:
@@ -107,5 +107,5 @@
 md.prognostic.spcthickness=NaN*ones(md.mesh.numberofvertices,1);
 md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
-md.thermal.spctemperature=737*ones(md.mesh.numberofvertices,1);
+md.thermal.spctemperature=737.*ones(md.mesh.numberofvertices,1);
 
 %Change name so that no test have the same name
Index: /issm/trunk/test/Par/RoundSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/RoundSheetShelf.py	(revision 13975)
+++ /issm/trunk/test/Par/RoundSheetShelf.py	(revision 13975)
@@ -0,0 +1,122 @@
+import os.path
+import numpy
+import copy
+import inspect
+from paterson import *
+from verbose import *
+
+#Start defining model parameters here
+
+di=md.materials.rho_ice/md.materials.rho_water
+rad=1.e6
+shelfextent=2.e5
+#Geometry
+hmin=300.
+hmax=1000.
+radius=numpy.sqrt(md.mesh.x*md.mesh.x+md.mesh.y*md.mesh.y)
+ymin=numpy.min(radius)
+ymax=numpy.max(radius)
+md.geometry.thickness=hmax+(hmin-hmax)*(radius-ymin)/(ymax-ymin)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+
+pos=numpy.nonzero(md.mask.vertexongroundedice)
+md.geometry.bed[pos]=md.geometry.bed[pos]-300.*(radius[pos]-(rad-shelfextent))/(rad-shelfextent)
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+pos=numpy.nonzero(radius<200000.)
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+pos=numpy.nonzero(numpy.logical_and(numpy.logical_and(md.mesh.x<0.2*1.e6,md.mesh.x>-0.2*1.e6),md.mesh.y>0.))
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+pos=numpy.nonzero(numpy.logical_and(numpy.logical_and(md.mesh.x<0.1*1.e6,md.mesh.x>-0.1*1.e6),numpy.logical_and(md.mesh.y<-0.5*1.e6,md.mesh.y>-0.6*1.e6)))
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+#plug holes into the ice sheet, to test for grounding line migration. 
+di=md.materials.rho_ice/md.materials.rho_water
+rad=numpy.sqrt(md.mesh.x**2+md.mesh.y**2)
+pos=numpy.nonzero(rad<200000.)
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+pos=numpy.nonzero(numpy.logical_and(numpy.logical_and(md.mesh.x<0.2*1.e6,md.mesh.x>-0.2*1.e6),md.mesh.y>0.))
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+pos=numpy.nonzero(numpy.logical_and(numpy.logical_and(md.mesh.x<0.1*1.e6,md.mesh.x>-0.1*1.e6),numpy.logical_and(md.mesh.y<-0.5*1.e6,md.mesh.y>-0.6*1.e6)))
+md.geometry.thickness[pos]=100.
+md.geometry.bed[pos]=-di*md.geometry.thickness[pos]-20.
+md.geometry.surface[pos]=md.geometry.bed[pos]+md.geometry.thickness[pos]
+
+#Initial velocity 
+md.initialization.vx=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.vy=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
+
+#Materials
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Surface mass balance and basal melting
+md.surfaceforcings.mass_balance=-10.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
+pos=numpy.nonzero(md.mask.vertexonfloatingice)
+md.basalforcings.melting_rate[pos]=10.
+md.basalforcings.geothermalflux=numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot=0.0
+md.prognostic.stabilization=1
+md.thermal.stabilization=1
+md.verbose=verbose(0)
+md.settings.waitonlock=30
+md.diagnostic.restol=0.05
+md.diagnostic.reltol=0.05
+md.steadystate.reltol=0.05
+md.diagnostic.abstol=float('nan')
+md.timestepping.time_step=5.
+md.timestepping.final_time=5.
+
+#bathymetry and grounding line migration:
+md.groundingline.migration='AgressiveMigration'
+md.geometry.bathymetry=copy.deepcopy(md.geometry.bed)
+pos=numpy.nonzero(md.mask.vertexonfloatingice)
+md.geometry.bathymetry[pos]=md.geometry.bed[pos]-900.
+
+#Deal with boundary conditions:
+md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+
+pos=numpy.nonzero(numpy.logical_and(md.mesh.x==0,md.mesh.y==0))
+md.diagnostic.spcvx[pos]=0
+md.diagnostic.spcvy[pos]=0
+
+pressureload=copy.deepcopy(md.mesh.segments)
+pressureload=numpy.hstack((pressureload,(1*md.mask.elementonfloatingice[pressureload[:,-1].astype(int)-1] + 0*md.mask.elementongroundedice[pressureload[:,-1].astype(int)-1]).reshape(-1,1)))
+md.diagnostic.icefront=pressureload
+md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
+md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
+md.thermal.spctemperature=737.*numpy.ones((md.mesh.numberofvertices,1))
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/SquareSheetConstrained.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 13974)
+++ /issm/trunk/test/Par/SquareSheetConstrained.par	(revision 13975)
@@ -6,6 +6,7 @@
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
+
 md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin);
-md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20;
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
 
@@ -16,4 +17,5 @@
 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);
@@ -23,11 +25,11 @@
 
 %Materials
-md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+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);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
 %Friction
 pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
 md.friction.coefficient(md.mesh.elements(pos,:))=0;
 md.friction.p=ones(md.mesh.numberofelements,1);
@@ -36,6 +38,6 @@
 %Numerical parameters
 md.diagnostic.viscosity_overshoot=0.0;
-md.prognostic.stabilization=1;
-md.thermal.stabilization=1;
+md.prognostic.stabilization=1.;
+md.thermal.stabilization=1.;
 md.verbose=verbose(0);
 md.settings.waitonlock=30;
@@ -44,6 +46,6 @@
 md.diagnostic.reltol=0.05;
 md.diagnostic.abstol=NaN;
-md.timestepping.time_step=1;
-md.timestepping.final_time=3;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
 
 %Boundary conditions:
Index: /issm/trunk/test/Par/SquareSheetConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 13975)
+++ /issm/trunk/test/Par/SquareSheetConstrained.py	(revision 13975)
@@ -0,0 +1,67 @@
+import os.path
+import netCDF4
+import numpy
+import inspect
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetIceSheetBC import *
+
+#Start defining model parameters here
+
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=numpy.min(md.mesh.y)
+ymax=numpy.max(md.mesh.y)
+
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness+20.
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+#Initial velocity 
+f = netCDF4.Dataset('../Data/SquareSheetConstrained.nc','r')
+x     = numpy.reshape(f.variables['x'][:],(-1))
+y     = numpy.reshape(f.variables['y'][:],(-1))
+vx    = f.variables['vx'][:]
+vy    = f.variables['vy'][:]
+index = f.variables['index'][:]
+f.close()
+
+[md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
+
+#Materials
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
+#Friction
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot=0.0
+md.prognostic.stabilization=1.
+md.thermal.stabilization=1.
+md.verbose=verbose(0)
+md.settings.waitonlock=30.
+md.diagnostic.restol=0.05
+md.steadystate.reltol=0.05
+md.diagnostic.reltol=0.05
+md.diagnostic.abstol=float('NaN')
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+
+#Boundary conditions:
+md=SetIceSheetBC(md)
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
+
Index: /issm/trunk/test/Par/SquareSheetShelf.par
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.par	(revision 13974)
+++ /issm/trunk/test/Par/SquareSheetShelf.par	(revision 13975)
@@ -2,6 +2,6 @@
 
 %Geometry
-hmin=300;
-hmax=1000;
+hmin=300.;
+hmax=1000.;
 ymin=min(md.mesh.y);
 ymax=max(md.mesh.y);
@@ -9,5 +9,5 @@
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness;
 bed_sheet=-md.materials.rho_ice/md.materials.rho_water*(hmax+(hmin-hmax)*(ymax/2-ymin)/(ymax-ymin));
-pos=find(md.mesh.y<=ymax/2);
+pos=find(md.mesh.y<=ymax/2.);
 md.geometry.bed(pos)=bed_sheet;
 md.geometry.surface=md.geometry.bed+md.geometry.thickness;
@@ -26,16 +26,16 @@
 
 %Materials
-md.initialization.temperature=(273-20)*ones(md.mesh.numberofvertices,1);
+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);
+md.materials.rheology_n=3.*ones(md.mesh.numberofelements,1);
 
 %Accumulation and melting
-md.surfaceforcings.mass_balance=10*ones(md.mesh.numberofvertices,1);
-md.basalforcings.melting_rate=5*ones(md.mesh.numberofvertices,1);
+md.surfaceforcings.mass_balance=10.*ones(md.mesh.numberofvertices,1);
+md.basalforcings.melting_rate=5.*ones(md.mesh.numberofvertices,1);
 
 %Friction
 pos=find(md.mask.elementonfloatingice);
-md.friction.coefficient=20*ones(md.mesh.numberofvertices,1);
-md.friction.coefficient(md.mesh.elements(pos,:))=0;
+md.friction.coefficient=20.*ones(md.mesh.numberofvertices,1);
+md.friction.coefficient(md.mesh.elements(pos,:))=0.;
 md.friction.p=ones(md.mesh.numberofelements,1);
 md.friction.q=ones(md.mesh.numberofelements,1);
@@ -51,6 +51,6 @@
 md.diagnostic.reltol=0.05;
 md.diagnostic.abstol=NaN;
-md.timestepping.time_step=1;
-md.timestepping.final_time=3;
+md.timestepping.time_step=1.;
+md.timestepping.final_time=3.;
 
 %Deal with boundary conditions:
Index: /issm/trunk/test/Par/SquareSheetShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareSheetShelf.py	(revision 13975)
+++ /issm/trunk/test/Par/SquareSheetShelf.py	(revision 13975)
@@ -0,0 +1,72 @@
+import os.path
+import inspect
+import netCDF4
+from numpy import *
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetMarineIceSheetBC import *
+
+#Start defining model parameters here
+
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+bed_sheet=-md.materials.rho_ice/md.materials.rho_water*(hmax+(hmin-hmax)*(ymax/2-ymin)/(ymax-ymin))
+pos=numpy.nonzero(md.mesh.y<=ymax/2.)
+md.geometry.bed[pos]=bed_sheet
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+#Initial velocity 
+f = netCDF4.Dataset('../Data/SquareSheetShelf.nc','r')
+x         = reshape(f.variables['x'][:],(-1))
+y         = reshape(f.variables['y'][:],(-1))
+vx        = f.variables['vx'][:]
+vy        = f.variables['vy'][:]
+index     = f.variables['index'][:]
+f.close()
+
+[md.initialization.vx]  = InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]  = InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+
+#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))
+
+#Accumulation and melting
+md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+
+#Friction
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos].astype(int)-1]=0.
+md.friction.p=ones((md.mesh.numberofelements,1))
+md.friction.q=ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot=0.0
+md.prognostic.stabilization=1
+md.thermal.stabilization=1
+md.verbose=verbose(0)
+md.settings.waitonlock=30.
+md.diagnostic.restol=0.05
+md.steadystate.reltol=0.05
+md.diagnostic.reltol=0.05
+md.diagnostic.abstol=float('NaN')
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+
+#Deal with boundary conditions:
+md=SetMarineIceSheetBC(md,'../Exp/SquareFront.exp')
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name = os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/SquareShelf.py
===================================================================
--- /issm/trunk/test/Par/SquareShelf.py	(revision 13975)
+++ /issm/trunk/test/Par/SquareShelf.py	(revision 13975)
@@ -0,0 +1,87 @@
+import os.path
+import inspect
+import netCDF4
+from numpy import *
+from verbose import *
+from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
+from paterson import *
+from SetIceShelfBC import *
+
+#Start defining model parameters here
+#Geometry
+hmin=300.
+hmax=1000.
+ymin=min(md.mesh.y)
+ymax=max(md.mesh.y)
+
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
+md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
+
+#Initial velocity and pressure
+iVelF = netCDF4.Dataset('../Data/SquareShelf.nc','r')
+
+x=reshape(iVelF.variables['x'][:],(-1))
+y=reshape(iVelF.variables['y'][:],(-1))
+vx=iVelF.variables['vx'][:]
+vy=iVelF.variables['vy'][:]
+index=iVelF.variables['index'][:].astype(float)
+index=reshape(index.T,(len(index),3),order='F')
+
+#dbg - begin
+# #print 'vars in SquareShelf.nc:'
+# #for v in iVelF.variables:
+# #	print v
+#dbg - end 
+
+iVelF.close()
+
+[md.initialization.vx]=InterpFromMeshToMesh2d(index,x,y,vx,md.mesh.x,md.mesh.y)
+[md.initialization.vy]=InterpFromMeshToMesh2d(index,x,y,vy,md.mesh.x,md.mesh.y)
+md.initialization.vz=zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=zeros((md.mesh.numberofvertices,1))
+
+#dbg - begin
+#print '...vx:'
+#print md.initialization.vx
+#print '...vy:'
+#print md.initialization.vy
+##print '...vz:'
+##print md.initialization.vz
+##print '...pressure:'
+##print md.initialization.pressure
+#dbg - end 
+
+
+#Materials
+md.initialization.temperature = (273.-20.)*ones((md.mesh.numberofvertices,1))
+md.materials.rheology_B = paterson(md.initialization.temperature)
+md.materials.rheology_n = 3.*ones((md.mesh.numberofelements,1))
+
+#Friction
+pos=nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient = 20.*ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1] = 0.
+md.friction.p = ones((md.mesh.numberofelements,1))
+md.friction.q = ones((md.mesh.numberofelements,1))
+
+#Numerical parameters
+md.diagnostic.viscosity_overshoot = 0.3
+md.prognostic.stabilization = 1.
+md.thermal.stabilization = 1.
+md.settings.waitonlock = 30.
+md.verbose=verbose()
+md.diagnostic.restol = 0.10
+md.steadystate.reltol = 0.02
+md.diagnostic.reltol = 0.02
+md.diagnostic.abstol = nan
+md.timestepping.time_step = 1.
+md.timestepping.final_time = 3.
+
+#Boundary conditions:
+# #md=SetIceShelfBC(md)
+md=SetIceShelfBC(md,'../Exp/SquareFront.exp')
+
+#Change name so that no test have the same name
+if len(inspect.stack()) > 2:
+	md.miscellaneous.name=os.path.basename(inspect.stack()[2][1]).split('.')[0]
Index: /issm/trunk/test/Par/SquareShelfConstrained.py
===================================================================
--- /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 13974)
+++ /issm/trunk/test/Par/SquareShelfConstrained.py	(revision 13975)
@@ -1,6 +1,6 @@
 import os.path
+import netCDF4
+import numpy
 import inspect
-import netCDF4
-from numpy import *
 from verbose import *
 from InterpFromMeshToMesh2d import InterpFromMeshToMesh2d
@@ -10,56 +10,60 @@
 #Start defining model parameters here
 #Geometry
-hmin = 300.
-hmax = 1000.
-ymin = min(md.mesh.y)
-ymax = max(md.mesh.y)
+hmin=300.
+hmax=1000.
+ymin=numpy.min(md.mesh.y)
+ymax=numpy.max(md.mesh.y)
 
-md.geometry.thickness = hmax+(hmin-hmax)*(md.mesh.y-ymin)/(ymax-ymin)
+md.geometry.thickness=hmax+(hmin-hmax)*(md.mesh.y.reshape(-1,1)-ymin)/(ymax-ymin)
 md.geometry.bed=-md.materials.rho_ice/md.materials.rho_water*md.geometry.thickness
-md.geometry.surface = md.geometry.bed+md.geometry.thickness
+md.geometry.surface=md.geometry.bed+md.geometry.thickness
 
 #Initial velocity 
 f = netCDF4.Dataset('../Data/SquareShelfConstrained.nc','r')
 #Reshape as Rank-1 arrays
-x=reshape(f.variables['x'][:],(-1))
-y=reshape(f.variables['y'][:],(-1))
+x=numpy.reshape(f.variables['x'][:],(-1))
+y=numpy.reshape(f.variables['y'][:],(-1))
 vx=f.variables['vx'][:]
 vy=f.variables['vy'][:]
-#deal with 'F' oriented matlab matrices!
-index=f.variables['index'][:].astype(float)
-index=reshape(index.T,(len(index),3),order='F')
+index=f.variables['index'][:]
 f.close()
 
-[md.initialization.vx] = InterpFromMeshToMesh2d(index, x, y, vx, md.mesh.x, md.mesh.y)
-[md.initialization.vy] = InterpFromMeshToMesh2d(index, x, y, vy, md.mesh.x, md.mesh.y)
-md.initialization.vz = zeros(md.mesh.numberofvertices)
-md.initialization.pressure = zeros(md.mesh.numberofvertices)
+[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=numpy.zeros((md.mesh.numberofvertices,1))
+md.initialization.pressure=numpy.zeros((md.mesh.numberofvertices,1))
+
 #Materials
-md.initialization.temperature = (273.-20)*ones(md.mesh.numberofvertices)
-md.materials.rheology_B = paterson(md.initialization.temperature)
-md.materials.rheology_n = 3.*ones(md.mesh.numberofelements)
+md.initialization.temperature=(273.-20.)*numpy.ones((md.mesh.numberofvertices,1))
+md.materials.rheology_B=paterson(md.initialization.temperature)
+md.materials.rheology_n=3.*numpy.ones((md.mesh.numberofelements,1))
+
 #Surface mass balance and basal melting
-md.surfaceforcings.mass_balance = 10.*ones(md.mesh.numberofvertices)
-md.basalforcings.melting_rate = 5.*ones(md.mesh.numberofvertices)
+md.surfaceforcings.mass_balance=10.*numpy.ones((md.mesh.numberofvertices,1))
+md.basalforcings.melting_rate=5.*numpy.ones((md.mesh.numberofvertices,1))
+
 #Friction
-pos = nonzero(md.mask.elementonfloatingice)
-md.friction.coefficient = 20.*ones(md.mesh.numberofvertices)
-md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1] =0.
-md.friction.p = ones(md.mesh.numberofelements)
-md.friction.q = ones(md.mesh.numberofelements)
+pos=numpy.nonzero(md.mask.elementonfloatingice)
+md.friction.coefficient=20.*numpy.ones((md.mesh.numberofvertices,1))
+md.friction.coefficient[md.mesh.elements[pos,:].astype(int)-1]=0.
+md.friction.p=numpy.ones((md.mesh.numberofelements,1))
+md.friction.q=numpy.ones((md.mesh.numberofelements,1))
+
 #Numerical parameters
-md.diagnostic.viscosity_overshoot = 0.0
-md.prognostic.stabilization = 1.
-md.thermal.stabilization = 1.
-md.verbose = verbose()
-md.settings.waitonlock = 30.
-md.diagnostic.restol = 0.05
-md.diagnostic.reltol = 0.05
-md.steadystate.reltol = 0.05
-md.diagnostic.abstol = nan
-md.timestepping.time_step = 1.
-md.timestepping.final_time = 3.
+md.diagnostic.viscosity_overshoot=0.0
+md.prognostic.stabilization=1.
+md.thermal.stabilization=1.
+md.verbose = verbose(0)
+md.settings.waitonlock=30.
+md.diagnostic.restol=0.05
+md.diagnostic.reltol=0.05
+md.steadystate.reltol=0.05
+md.diagnostic.abstol=float('nan')
+md.timestepping.time_step=1.
+md.timestepping.final_time=3.
+
 #Deal with boundary conditions:
 md = SetIceShelfBC(md)
+
 #Change name so that no tests have the same name
 if len(inspect.stack()) > 2:
